Skip to content

Instantly share code, notes, and snippets.

@glucero
Last active December 20, 2015 05:59
Show Gist options
  • Save glucero/6082837 to your computer and use it in GitHub Desktop.
Save glucero/6082837 to your computer and use it in GitHub Desktop.
chutes and ladders turn count analysis
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
@glucero
Copy link
Author

glucero commented Jul 25, 2013

(main) > ChutesAndLadders.run(1_000)
Number of Games:    1000
Total Turns:        37378
Min Turns:          6
Max Turns:          166
Mean Turns:         37.378
Standard Deviation: 23.798174635883296

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment