Monty Hall in Ruby
April 01 2013 03:00 CET
The Monty Hall Problem is one of the more weird statistical paradoxes.
Yesterday, while trying to convicing my fiancée why changing your initial choice would give you better odds, I realized that writing a small Ruby Monte Carlo simulator of the problem might be a fun little challenge.
How few lines of code would it take in Ruby, while still maintaining readability?
I came up with the code below. If you can improve on it I’d love to hear!
def monty(switch)
correct_answer, answer = rand(3), rand(3)
open_door = ([0,1,2] - [answer,correct_answer]).first
answer = ([0,1,2] - [answer,open_door]).first if switch
answer == correct_answer
end
[true, false].each do |switch|
wins = 0
10_000.times { wins += 1 if monty(switch) }
puts "#{switch ? "Not sticking" : "Sticking"} with choice win rate: #{(wins.to_f/10_000*100).round} %"
end