Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Created May 31, 2018 17:00
Show Gist options
  • Save Bodacious/2d1bb1c312eecff0d2328795ee36a513 to your computer and use it in GitHub Desktop.
Save Bodacious/2d1bb1c312eecff0d2328795ee36a513 to your computer and use it in GitHub Desktop.
Monty Hall Problem demonstrated in Ruby
class Game
attr_accessor :doors
attr_reader :correct_door
def initialize(door_count: )
chosen_door = (1..door_count).to_a.sample
@doors = door_count.times.map.with_index do |d, i|
Door.new(i+1 == chosen_door)
end
@correct_door = @doors.detect(&:correct?)
end
def remove_one_door!(not_door: )
removing = @doors.detect { |d| d != not_door && !d.correct? }
@doors.delete(removing)
end
end
class Door
attr_reader :correct
alias correct? correct
def initialize(correct)
@correct = !!correct
end
end
class Try
attr_reader :player
attr_reader :game
attr_reader :outcome
def initialize(player:, game:)
@player = player
@game = game
@outcome = nil
end
def play!
player.make_choice!(game)
game.remove_one_door!(not_door: player.chosen_door)
player.make_choice!(game)
@outcome = game.correct_door == player.chosen_door
end
def win?
outcome == true
end
end
class Player
attr_accessor :strategy
attr_accessor :chosen_door
def initialize(strategy)
@strategy = strategy
end
def make_choice!(game)
if chosen_door && strategy == :stick
return chosen_door
else
return @chosen_door = game.doors.sample
end
end
end
TIMES_PLAYED = 1_000_000
win_count = 0
TIMES_PLAYED.times do
try = Try.new(player: Player.new(:stick), game: Game.new(door_count: 3))
win_count += 1 if try.play! && try.win?
end
puts "Stick wins: #{win_count} #{Rational(win_count, TIMES_PLAYED).to_f * 100}%"
win_count = 0
TIMES_PLAYED.times do
try = Try.new(player: Player.new(:switch), game: Game.new(door_count: 3))
win_count += 1 if try.play! && try.win?
end
puts "Switch wins: #{win_count} #{Rational(win_count, TIMES_PLAYED).to_f * 100}%"
@Bodacious
Copy link
Author

Bodacious commented May 31, 2018

Stick wins: 332984 (33.2984%)
Switch wins: 499476 (49.947599999999994%)

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