Last active
August 29, 2015 14:02
-
-
Save jmmastey/0ee5653cd8cd1242deb7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DiceStats | |
attr_accessor :stats, :die | |
def initialize(args = {}) | |
@die = args[:die] || 6 | |
@tests = args[:tests] || [10, 100, 1_000, 10_000, 100_000, 1_000_000] | |
@format = args[:format] || generate_default_format | |
@stats = {} | |
run_experiments | |
end | |
def stats_table | |
table = "# of Rolls" | |
(1..@die).each { |n| table << "%8ds" % n } | |
table << "\n#{'#' * 66}\n" | |
@tests.each { |test| table << format_experiment(test, @stats[test]) } | |
table | |
end | |
private | |
def generate_default_format | |
"%-12d" + (" | %05.2f%%" * @die) + "\n" | |
end | |
def format_experiment(total, stats) | |
percentages = stats.values.map { |num| (num / total.to_f) * 100 } | |
@format % ([ total ] + percentages) | |
end | |
def run_experiments | |
@tests.each do |test| | |
run_experiment(test) | |
end | |
stats | |
end | |
def run_experiment(size) | |
results = new_stats_hash | |
size.times do | |
roll = roll_dice | |
results[roll] += 1 | |
end | |
stats[size] = results | |
end | |
def new_stats_hash | |
(0...@die).inject({}) do |hash,n| | |
hash[n] = 0 | |
hash | |
end | |
end | |
def roll_dice | |
rand(@die) | |
end | |
end | |
dice = DiceStats.new | |
puts dice.stats_table |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# of Rolls 1s 2s 3s 4s 5s 6s | |
################################################################## | |
10 | 20.00% | 20.00% | 40.00% | 20.00% | 00.00% | 00.00% | |
100 | 19.00% | 14.00% | 18.00% | 20.00% | 11.00% | 18.00% | |
1000 | 16.20% | 16.40% | 14.50% | 18.40% | 15.90% | 18.60% | |
10000 | 16.69% | 17.13% | 15.87% | 16.87% | 16.73% | 16.71% | |
100000 | 16.73% | 16.58% | 16.83% | 16.70% | 16.73% | 16.43% | |
1000000 | 16.64% | 16.68% | 16.68% | 16.67% | 16.69% | 16.65% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment