Skip to content

Instantly share code, notes, and snippets.

@robesris
Created December 5, 2014 21:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save robesris/f894730331d87e9cfc36 to your computer and use it in GitHub Desktop.
A demo proving the Monty Hall problem, in Ruby
TRIES = 1000
successes = 0.0
1.upto(TRIES) do
doors = [:goat, :goat, :goat]
# put a car behind a random door
doors[(rand * 3).to_i] = :car
puts "1: #{doors[0]}"
puts "2: #{doors[1]}"
puts "3: #{doors[2]}"
# pick a door at random
choice = (rand * 3).to_i
puts "Chose door ##{choice + 1}..."
#open one of the other doors that has a goat, at random
other_doors_with_no_car_indices = (doors.each_with_index.map{ |e, i| i}).reject{|i| i == choice || doors[i] == :car}
open_door_index = other_doors_with_no_car_indices[(rand * other_doors_with_no_car_indices.length).to_i]
puts "Host reveals a goat behind door ##{open_door_index + 1}..."
#switch to the remaining door
indices = [0, 1, 2]
indices.delete(choice)
indices.delete(open_door_index)
final_door_index = indices.first
puts "Switching to door ##{final_door_index + 1}...found a #{doors[final_door_index]}."
if doors[final_door_index] == :car
puts "WIN!"
successes += 1
else
puts "FAIL."
end
end
puts "-------------"
puts "Succeeded by switching in #{successes} out of #{TRIES} tries."
puts "Sucess rate: #{successes / TRIES * 100.0}%"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment