Skip to content

Instantly share code, notes, and snippets.

@matpowel
Created February 22, 2015 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matpowel/626588e28be2a582dd05 to your computer and use it in GitHub Desktop.
Save matpowel/626588e28be2a582dd05 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulator
number_of_doors = 3
monty_is_random = false
switch_choice = true
number_of_simulations = 10000
# number_of_correct_initial_guesses = 0
number_of_times_monty_accidentally_exposes_car = 0
number_of_wins = 0
doors = (1..number_of_doors).inject({}){|h,i| h[i] = nil; h }
# => {1=>nil, 2=>nil, 3=>nil}
door_with_car_behind_it = rand(number_of_doors) + 1
doors[door_with_car_behind_it] = "CAR"
doors.keys.each{|door_number| doors[door_number] ||= "Camel" }
# => (eg.) {1=>"CAR", 2=>"Camel", 3=>"Camel"}
number_of_simulations.times do
first_guess = rand(number_of_doors) + 1
montys_remaining_choices = doors.keys - [first_guess]
if monty_is_random
exposed = false
while montys_remaining_choices.size > 1 && !exposed
montys_door = montys_remaining_choices[rand(montys_remaining_choices.size)]
if doors[montys_door] == "CAR"
number_of_times_monty_accidentally_exposes_car += 1
exposed = true
else
montys_remaining_choices -= [montys_door]
end
end
next if exposed
else
if doors[first_guess] == "CAR"
# Just choose any of the remaining doors to keep closed, might as well be the first
montys_remaining_choices = montys_remaining_choices[0..0]
else
# Keep the CAR door closed
montys_remaining_choices = [door_with_car_behind_it]
end
end
raise "Oops" unless montys_remaining_choices.size == 1
if switch_choice
new_guess = montys_remaining_choices[0]
else
new_guess = first_guess
end
if doors[new_guess] == "CAR"
number_of_wins += 1
end
end
percent_of_all = (number_of_wins.to_f / number_of_simulations)*100
percent_of_valid = (number_of_wins.to_f / (number_of_simulations - number_of_times_monty_accidentally_exposes_car))*100
puts "Player won #{number_of_wins} times or #{percent_of_all.round(1)}% of all simulations.\n" +
"Monty accidentally exposed the car #{number_of_times_monty_accidentally_exposes_car} times.\n" +
"Therefore player won #{percent_of_valid.round(1)}% of valid simulations"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment