Skip to content

Instantly share code, notes, and snippets.

@jonhinson
Created October 14, 2011 22:58
Show Gist options
  • Save jonhinson/1288605 to your computer and use it in GitHub Desktop.
Save jonhinson/1288605 to your computer and use it in GitHub Desktop.
Demonstration of the Monty Hall problem and that a switching strategy is always better ( you win 2/3 of the time).
class Monty
STAY = true
SWITCH = false
def initialize(strat = STAY)
@strategy = strat
@times_won = 0
end
def play(n)
n.times do
choices = self.doors
first_pick = rand(3)
# eliminate the door that was not picked and is not a car.
choices.each_with_index { |choice, door| choices[door] = nil if first_pick != door and choice != "car" }
self.outcome(first_pick, choices)
end
puts "You won %d%% of the time with a %s strategy." % [((@times_won.to_f / n) * 100), @strategy ? "staying" : "switching"]
end
protected
def doors
["car", "goat", "goat"].shuffle
end
def outcome(first_pick, choices)
if @strategy
# Staying strategy, just examine our first pick
@times_won += choices[first_pick] == "car" ? 1 : 0
else
# Switch strategy, eliminate our choice and check the remaininder
choices[first_pick] = nil
choices.compact!
@times_won += choices.first == "car" ? 1 : 0
end
end
end
game = Monty.new(Monty::STAY)
game.play(100000)
game = Monty.new(Monty::SWITCH)
game.play(100000)
# OUTPUT:
# You won 33% of the time with a staying strategy.
# You won 66% of the time with a switching strategy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment