Wednesday, July 27, 2016

Monty Hall Problem

I first heard of the Monty Hall Problem while watching the TV show "Numb3rs".

The main character of the show is a math genius who frequently helps solve crimes using his math skills.

I don't remember the details of the episode, but they were talking about game theory and the Monty Hall problem came up.

It came to my attention again today while reading this StackExchange Question

Here's how it goes:

    Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?"

    Is it to your advantage to switch your choice?

It turns out that, even if it doesn't seem intuitive, you are more likely to win if you switch. Mathematicians argued about it, but have finally agreed.

I wanted to write a quick bit of code to see what probability I came up with. My language of choice at the moment is PHP, so here it is:

You can run it here:
(Don't be confused. In that sandbox, instead of "doors", I used "cards" )




for ($i=0; $i <= 100000; $i++) {



$known_car=array_search('car', $doors);


//trying to write this made it obvious to me WHY you should always switch


unset($hosts_choices[$player_choice]); // The host cannot choose the player's door.

unset($hosts_choices[$known_car]); // The host cannot choose the car.



$hosts_choice=reset($hck); // at this point, the host will only have 1 or 2 doors to choose from.


if ($doors[$player_choice]=='car') {






echo 'Players who did not swap would have won '. $player_should_keep . ' times'."


echo 'Players who did swap would have won '. $player_should_swap . ' times'."



The funny thing is, I realized after I wrote it that I could comment out the biggest part of the logic, and the code still works. I never actually did anything with the edited version of the $doors array. I could, if there were a skeptic that needed to see actual guesses and actual outcomes, but it isn't really necessary.

Think of it this way, if I have a 1:3 chance selecting the car on the first go, there is a 2:3 chance I didn't choose a car. The host always removes a goat, so my choice is to believe that my 1:3 guess was right and stick to it, or to decide that I was probably wrong, and therefor switch. In the 2/3 of cases, where a goat was chosen and the other goat was removed, the only door left is the winning door.

Because I stepped through the logic in the PHP above, I could actually write a guessing routine, but I shortened it when I realized all I had to calculate was if the player SHOULD switch. Then, thinking about and writing this blog post made me realize how little of the PHP code I actually needed, and how obvious (retrospectively obvious) it is that switching is the preferred choice.