Last active
December 20, 2015 05:59
-
-
Save glucero/6082837 to your computer and use it in GitHub Desktop.
chutes and ladders turn count analysis
This file contains 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
module ChutesAndLadders | |
class Game | |
# chutes ladders | |
Board = {16 => 6, 1 => 23, | |
48 => 26, 4 => 14, | |
49 => 11, 9 => 31, | |
56 => 53, 21 => 42, | |
62 => 19, 28 => 84, | |
64 => 60, 36 => 44, | |
87 => 24, 51 => 67, | |
93 => 73, 71 => 91, | |
95 => 75, 80 => 100, | |
98 => 78} | |
attr_reader :turn | |
def initialize | |
@turn = @square = 0 | |
end | |
def dice | |
1 + rand(6) | |
end | |
def complete? | |
@square > 100 | |
end | |
def next_turn | |
square = @square + dice | |
Board[square] || square | |
end | |
def play! | |
until complete? | |
@turn += 1 | |
@square = next_turn | |
end | |
end | |
end | |
class Counter | |
include Enumerable | |
def initialize(games) | |
@games = games.each(&:play!) | |
end | |
def each | |
@games.each { |game| yield game.turn } | |
end | |
def sum | |
@sum ||= inject(&:+) | |
end | |
def mean | |
@mean ||= sum.to_f / count | |
end | |
def stddev | |
@stddev ||= begin | |
total = inject(0) { |total, turn| total + (turn - mean) ** 2 } | |
Math.sqrt(total.to_f / count) | |
end | |
end | |
end | |
def self.run(count = 100) | |
games = Array.new(count) { Game.new } | |
counter = Counter.new(games) | |
puts "Number of Games: #{counter.count}" | |
puts "Total Turns: #{counter.sum}" | |
puts "Min Turns: #{counter.min}" | |
puts "Max Turns: #{counter.max}" | |
puts "Mean Turns: #{counter.mean}" | |
puts "Standard Deviation: #{counter.stddev}" | |
end | |
end |
Author
glucero
commented
Jul 25, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment