Created
September 8, 2011 19:17
-
-
Save kejadlen/1204413 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
#!/usr/bin/env ruby | |
# monte carlo simulation for mini | |
class Mini | |
attr_reader :score | |
def initialize(*p) | |
@p = p | |
@score = [0, 0] | |
end | |
def play | |
@team = 0 # start with team 0 | |
self.play_point | |
end | |
def play_point | |
if rand < @p[@team] # scored! | |
@score[@team] += 1 | |
else # turnover! | |
@score[@team] -= 1 | |
@team = (@team + 1) % 2 | |
end | |
self.play_point unless self.over? | |
end | |
def over? | |
score.include?(3) or score.include?(-2) | |
end | |
def reset | |
@score = [0, 0] | |
end | |
end | |
n = 10_000 | |
scores = Hash.new { 0 } | |
m = Mini.new(0.5, 0.5) | |
n.times do | |
m.reset | |
m.play | |
scores[m.score] += 1 | |
end | |
scores.sort.reverse.each do |k,v| | |
puts "#{k.to_s.ljust(8)}: #{v / n.to_f}" | |
end | |
print "Winning %: " | |
puts scores.select {|k,_| k[0] == 3 or k[1] == -2 }.values.inject {|n,i| n + i } / n.to_f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment