Skip to content

Instantly share code, notes, and snippets.

@genezys
Last active September 27, 2015 08:48
Show Gist options
  • Save genezys/1243427 to your computer and use it in GitHub Desktop.
Save genezys/1243427 to your computer and use it in GitHub Desktop.
Monty Hall simulation
class Array
def random_value
self[rand(size)]
end
end
class MonthyHall
def initialize
@doors = [:goat, :goat, :goat]
@doors[rand(3)] = :car
end
def choose!(index = nil)
index ||= @choice
index %= @doors.size
@choice = index
# Take one of the remaining goats and open it
goats_indices = @doors.enum_for(:each_with_index).select{ |d, i| d == :goat && i != @choice }.map{ |d, i| i }.to_a
@doors[goats_indices.random_value] = :open
end
def change!
other_closed_indices = @doors.enum_for(:each_with_index).select{ |d, i| d != :open && i != @choice }.map{ |d, i| i }.to_a
@choice = other_closed_indices.random_value
end
def win?
@doors[@choice] == :car
end
end
class Player
def initialize(game)
@game = game
end
def win?
@game.choose!(rand(3))
choose!
@game.win?
end
protected
def choose!
end
end
class Smart < Player
def choose!
@game.change!
end
end
class Dumb < Player
def choose!
end
end
smart_wins = (1..1000).inject(0) do |count, iteration|
game = MonthyHall.new
player = Smart.new(game)
count + (player.win? ? 1 : 0)
end
dumb_wins = (1..1000).inject(0) do |count, iteration|
game = MonthyHall.new
player = Dumb.new(game)
count + (player.win? ? 1 : 0)
end
puts "Smart: #{smart_wins / 1000.0}"
puts "Dumb: #{dumb_wins / 1000.0}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment