我有一系列随机数字供抽奖用。
我怎样才能选择第二名的随机数等等,而不冒出第一名的风险呢?
$first = rand(0..99999)
$second = rand(0..99999)
$third = rand(0..99999)我需要在下面的图纸中得到一些例外。
发布于 2013-11-25 12:27:50
shuffle将对整个数组进行置换,这对于大型数组来说可能比较慢。sample是一个更快的操作
(1..99999).to_a.sample(3)为制定基准:
> require 'benchmark'
> arr = (0..99999).to_a; 0
> Benchmark.realtime { 10_000.times { arr.sample(3) } }
=> 0.002874
> Benchmark.realtime { 10_000.times { arr.shuffle[0,3] } }
=> 18.107669发布于 2013-11-25 12:58:49
如果您从一个大数组中选择一个非常小的数字,那么只获取3个随机数并检查它们是否不同可能是明智的:
def create_array_and_pick_three
arr = (0..99999).to_a
arr.sample(3)
end
def get_three_random_until_uniq
array, num = [], 3
array = (1..num).map{rand(0..99999)} until array.uniq.size == num
end
p Benchmark.realtime { 1000.times { create_array_and_pick_three }} #=> 4.343435
p Benchmark.realtime { 1000.times { get_three_random_until_uniq }} #=> 0.002对于您来说,确切的速度取决于数组的大小和所需的随机数的数量。
https://stackoverflow.com/questions/20192861
复制相似问题