Last active
February 22, 2020 20:41
-
-
Save ndp/7d54e3a5dc94a1c58618d4bd1592edb6 to your computer and use it in GitHub Desktop.
Simulate the Monty Hall problem in Ruby
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
class MontyHall | |
DOORS = 0..2 | |
def initialize | |
@car = rand(DOORS) | |
end | |
def pick | |
@pick = rand(DOORS) | |
end | |
def reveal | |
@reveal = rand(DOORS) | |
while @reveal == @car || @reveal == @pick | |
@reveal = rand(DOORS) | |
end | |
end | |
def stay_wins? # 33% | |
@car == @pick | |
end | |
def new_pick_wins? # 50% | |
new_pick = closed_doors[rand(2)] | |
new_pick == @car | |
end | |
def switch_wins? # 66% | |
@pick != @car #&& @reveal != @car | |
end | |
def closed_doors | |
DOORS.to_a - [@reveal] | |
end | |
def self.simulate(n) | |
switch_wins, stay_wins, new_pick_wins = 0, 0, 0 | |
n.times do | |
game = MontyHall.new | |
game.pick | |
game.reveal | |
stay_wins += 1 if game.stay_wins? | |
switch_wins += 1 if game.switch_wins? | |
new_pick_wins += 1 if game.new_pick_wins? | |
end | |
puts "stay_wins = #{1.0 * stay_wins / n}" | |
puts "new_pick_wins = #{1.0 * new_pick_wins / n}" | |
puts "switch_wins = #{1.0 * switch_wins / n}" | |
# stay_wins = 0.333176 | |
# new_pick_wins = 0.500569 | |
# switch_wins = 0.666824 | |
end | |
end | |
MontyHall.simulate 1_000_000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment