Skip to content

Instantly share code, notes, and snippets.

@rampantmonkey
Created October 21, 2013 16:22
Show Gist options
  • Save rampantmonkey/7086635 to your computer and use it in GitHub Desktop.
Save rampantmonkey/7086635 to your computer and use it in GitHub Desktop.
Dice rolling. Compute the probability of rolling n 2's with i dice.
#!/usr/bin/env ruby
class Die
def initialize sides=6
@sides = sides
end
def roll
Random.rand(1..@sides)
end
end
if ARGV.length != 3
puts "Usage: dice_rolling.rb target dice_count iterations"
exit(1)
end
target = ARGV[0].to_i
dice_count = ARGV[1].to_i
iterations = ARGV[2].to_i
histogram = Hash.new { |h, k| h[k] = 0 }
dice = Array.new dice_count, Die.new
iterations.times do |j|
count = dice.map{|d| d.roll}
.select{|r| r == target}
.length
histogram[count] += 1
end
(dice_count+1).times {|i| print "(#{i}: #{histogram[i]}) "}
print "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment