编写 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 位数字。有什么建议吗?
最佳答案
这为您提供了 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)
并在输出每个值时添加前导零。根据this post 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)
关于ruby - 在 Ruby 中最快实现随机数生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4369857/