Skip to content

Instantly share code, notes, and snippets.

@roryokane
Created June 9, 2012 02:24
Show Gist options
  • Save roryokane/2899137 to your computer and use it in GitHub Desktop.
Save roryokane/2899137 to your computer and use it in GitHub Desktop.
likelihood of dice rolls when you roll four six-sided dice, take the top three
#encoding: utf-8
# http://news.ycombinator.com/item?id=4086325
# … try to generate a table of how likely it was to get various dice rolls when you rolled 4 6-sided dice and took the top 3.
require 'pp'
def dice_roll(sides)
rand(sides) + 1
end
def run_trials(num_trials, num_sides, num_dice, num_low_to_remove)
results = Array.new
num_trials.times do
rolls = (1..num_dice).map do
dice_roll(num_sides)
end
higher_rolls = rolls.sort[num_low_to_remove..-1]
results.push higher_rolls
end
results
end
def results_string(results)
results.map{|result|result.join(" ")}.join("\n")
end
def count_number_occurrences(results)
counts = Hash.new(0)
results.each do |result|
result.each do |number|
counts[number] += 1
end
end
counts.sort
end
def inspect_count(count)
count.map do |number_count|
number = number_count[0]
count = number_count[1]
"#{number} × #{count}"
end.join("\n")
end
num_trials = 1000000
num_sides = 6
num_dice = 4
num_low_to_remove = 1
results = run_trials(num_trials, num_sides, num_dice, num_low_to_remove)
# puts results_string(results)
count = count_number_occurrences(results)
puts inspect_count(count)
1 × 149134
2 × 380883
3 × 532604
4 × 617414
5 × 654096
6 × 665869
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment