Created
December 5, 2014 21:23
-
-
Save robesris/f894730331d87e9cfc36 to your computer and use it in GitHub Desktop.
A demo proving the Monty Hall problem, in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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