# An Engineer's approach to the Monty Hall problem

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?

The Monty Hall problem is a famous probability puzzle with a counter-intuitive solution. Most people (including me) initially assume that, once the first goat is revealed, the remaining two doors have an equal probability of containing the car and so switching does not matter. In fact, we gain information when the host eliminates one of the doors, and the door he did not pick becomes our best bet. If we switch, we have a two-thirds chance of winning the car.

Rather than think too deeply, we can write a few lines of Octave to play the game a thousand times and see which strategy, stay or switch doors, comes out on top.

```
N = 1000; % Number of trials
% Suppose, without loss of generality, our initial choice is always door 1
% Door index containing the car, 1 to 3
i_car = randi(3,N,1);
% Preallocate index for which of the remaining doors is revealed
i_reveal = nan(N,1);
% Reveal a random choice of 2 and 3 when car behind 1
i_reveal(i_car==1) = randi(2,sum(i_car==1),1)+1;
% Only one reveal option if we did not pick the car first
i_reveal(i_car==2) = 3; % Reveal 3 when car behind 2
i_reveal(i_car==3) = 2; % Reveal 2 when car behind 3
% Index for the door that we could switch to
% Yields 3 if Monty revealed 2, and vice versa
i_switch = (i_reveal==2)+2;
% If we do not switch, then we win if the car is behind door 1
win_no_switch = (i_car == 1);
% If we do switch, then we win if the car is behind the switch index
win_switch = (i_car == i_switch);
fprintf('No-switch win probability: %.2f\n',sum(win_no_switch)/N)
fprintf('Switch win probability: %.2f\n',sum(win_switch)/N)
```

If we run this script (try it online!) we get,

No-switch win probability: 0.34

Switch win probability: 0.66

which is what we were expecting. Sometimes, it is more reliable to throw a computer at a problem than to carefully work things out by hand.