Close

K iteration steps simulation in Ruby

Adi Oltean reported an interesting problem in his blog.


Say that you have an array of N boolean values, with all values initially set to FALSE. At each iteration step, you arbitrary pick an element in the array and set it to TRUE. What is the average number of elements set to TRUE after K iteration steps?


Soon there were solutions posted by Nicholas Allen and ReuvenLax in the comments  section. The nerd who actually wrote a simulation of this was Neal Hardesty! Following is his code.


# Usage: ruby testrand.rb <loops> <N sized array> <K rand elements>


loops=ARGV[0].to_i
n=ARGV[1].to_i
k=ARGV[2].to_i
runningTotal = 0

loops.times { |iLoop|
        a = []
        n.times { a[ (rand * 1000).to_i ] = 1 }
        total = 0
        k.times { |iK| total += 1 if a[iK]}
        runningTotal += total
}

puts "avg for #{n} sized array, #{k} rands, #{loops} iterations: " + (runningTotal / loops).to_s


and don't forget to try ruby! (in your browser)

Share