编写ruby随机数生成器的最快方法是什么?有没有这方面的学术公式?
我正在这样做,对于10,000个随机数,它需要大约4秒钟:
def generate_random_num(count = 1)
count.times.map do |i|
# make a setting!
num = rand(99999)
num = "0" * (5 - num.to_s.length) + num.to_s
redo if codes.include?(num)
codes << num
end
end
我只想生成最多99999个随机数,全部5位数。有什么提示吗?
答案 0 :(得分:5)
这为您提供了10000个带有前导零的唯一数字(字符串):
(1..10000).to_a.shuffle!.map{|n| n.to_s.rjust(5,'0')}
基准(使用Benchmark.measure):
user system total real
0.020000 0.000000 0.020000 ( 0.017471)
但是,我会使用:
(1..10000).to_a.shuffle!
哪个更快:
user system total real
0.000000 0.000000 0.000000 ( 0.001692)
输出每个值时添加前导零。根据{{3}} Ruby的shuffle
使用了Saeed提到的Fisher-Yates算法。
因此,要回答您的问题,您可以使用以下代码在[0,99999]范围内生成10000个唯一随机数:
(0..99999).to_a.shuffle!.slice(0..9999).map{|n| n.to_s.rjust(5, '0')}
基准:
user system total real
0.020000 0.000000 0.020000 ( 0.026122)