Fastest Implementation of a Random Number Generator in Ruby?
Whats the fastest way to write a ruby random number generator? Are there academic formulas for this?
I'm doin开发者_运维问答g this, and for 10,000 random numbers it takes about ~4 seconds:
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
I'm just trying to generate up to 99999 random numbers, all 5 digits. Any tips?
This gives you 10000 unique numbers (strings) with leading zeroes:
(1..10000).to_a.shuffle!.map{|n| n.to_s.rjust(5,'0')}
Benchmark (using Benchmark.measure):
user system total real
0.020000 0.000000 0.020000 ( 0.017471)
I would, however, just use:
(1..10000).to_a.shuffle!
Which is faster:
user system total real
0.000000 0.000000 0.000000 ( 0.001692)
And add the leading zeroes when you output each value. According to this post Ruby's shuffle
use the Fisher-Yates algorithm Saeed mentions.
Update:
So to answer your question, you could generate 10000 unique random numbers in the range [0,99999] with the following code:
(0..99999).to_a.shuffle!.slice(0..9999).map{|n| n.to_s.rjust(5, '0')}
With a benchmark of:
user system total real
0.020000 0.000000 0.020000 ( 0.026122)
精彩评论