Skip to content

Instantly share code, notes, and snippets.

@omnikron
Forked from bjjb/monty.rb
Last active August 29, 2015 13:56
Show Gist options
  • Save omnikron/9171355 to your computer and use it in GitHub Desktop.
Save omnikron/9171355 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Monty Hall problem proof http://en.wikipedia.org/wiki/Monty_Hall_problem
module Monty
PLAYERS_WITH_POLICY = { jimmy: :switch, jasper: :stick, johnson: :random }
DOORS = [:goat, :goat, :ferrari]
COUNT = Integer(ARGV[0] || 100000)
class << self
def win?(policy)
doors = DOORS.dup.shuffle
first_choice = doors.pop
remove_goat! doors
final_choice = case policy
when :stick then first_choice
when :switch then doors.sample
when :random then [true, false].sample ? first_choice : doors.sample
end
final_choice == :ferrari ? true : false
end
def remove_goat!(doors)
doors.slice!(doors.index(:goat))
end
def present(results_hash)
results_hash.each do |player, wins|
win_percentage = ((wins / COUNT) * 100.0).round(2)
puts "#{player.capitalize} used strategy #{PLAYERS_WITH_POLICY[player]} and won #{win_percentage}% of his #{COUNT} games"
end
end
def play
PLAYERS_WITH_POLICY.inject(Hash.new(0.0)) do |results, (player, policy)|
COUNT.times { results[player] += 1 if win?(policy) }
results
end
end
end
end
Monty.present Monty.play
@omnikron
Copy link
Author

$ time ruby oli.rb 10000000

Jimmy used strategy switch and won 66.66% of his 10000000 games
Jasper used strategy stick and won 33.35% of his 10000000 games
Johnson used strategy random and won 50.02% of his 10000000 games

real        1m34.006s
user        1m33.934s
sys         0m0.174s

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