Last Updated: January 28, 2019
·
765
· phs

Monty Hall in 30 lines

The Monty Hall problem is a mathematical puzzle featuring a strikingly counter-intuitive solution.

It's couched as a story about a game show. In it, the host (Monty) shows you three closed doors and tells you that behind one is a new car, but behind each of the other two is a goat. You'll choose a door and win whatever is behind (to be clear, you want the car.) To give you a sporting chance, Monty will give you a hint and an opportunity to change your mind.

Specifically,

  • You choose one of the 3 closed doors.
  • Monty opens one of the other two doors and shows you a goat.
  • He then asks if you'd like to change your mind, and opt for the remaining closed door.
  • You make your choice & take your prize.

The question is, should you change your mind or not? Overwhelmingly, most people conclude that the choice can't possibly matter: it's a 50-50 either way. It isn't. You actually should always choose to switch, as it doubles your odds of winning!

Since you probably don't believe me, go ahead and paste in this ruby ditty & convince yourself. For (several) explanations of this effect, see the wikipedia page.

#! /usr/bin/env ruby

# http://en.wikipedia.org/wiki/Monty_Hall_problem
def monty(switch)
  doors = (0...3).to_a
  winner = rand(doors.size)
  guess = rand(doors.size)

  revealable = doors - [guess, winner]
  revealed = revealable[rand(revealable.size)]
  other = (doors - [guess, revealed]).first

  guess = other if switch
  guess == winner
end

TRIALS = 10000
won_staying, won_switching = 0, 0
(0...TRIALS).each do |trial|
  won_staying   += 1 if monty(false)
  won_switching += 1 if monty(true)
end

puts "Win frequencies in Monty Hall when"
puts "    staying: #{100.0 * won_staying / TRIALS}%"
puts "  switching: #{100.0 * won_switching / TRIALS}%"

# Win frequencies in Monty Hall when
#     staying: 33.03%
#   switching: 66.38%