RosettaCodeData/Task/Average-loop-length/Ruby/average-loop-length.rb

26 lines
628 B
Ruby
Raw Permalink Normal View History

2014-01-17 05:32:22 +00:00
class Integer
def factorial
self == 0 ? 1 : (1..self).inject(:*)
end
end
def rand_until_rep(n)
rands = {}
2014-04-02 16:56:35 +00:00
loop do
r = rand(1..n)
2014-01-17 05:32:22 +00:00
return rands.size if rands[r]
rands[r] = true
end
end
runs = 1_000_000
2014-04-02 16:56:35 +00:00
puts " N average exp. diff ",
"=== ======== ======== ==========="
2014-01-17 05:32:22 +00:00
(1..20).each do |n|
sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_until_rep(n)}
avg = sum_of_runs / runs.to_f
analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)}
2014-04-02 16:56:35 +00:00
puts "%3d %8.4f %8.4f (%8.4f%%)" % [n, avg, analytical, (avg/analytical - 1)*100]
2014-01-17 05:32:22 +00:00
end