TQ
dev.com

Blog about software development

Subscribe

A Monte Carlo simulation of the Monty Hall problem

20 Aug 2025 - by 'Maurits van der Schee'

The Monty Hall problem is a probability puzzle. It has no logical contradiction, but for many people the result goes against their intuition. The problem originates from the American television game show "Let's Make a Deal". It is named after its original host, Monty Hall. The problem is stated as:

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, nothing. 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 nothing. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?

The problem can be simplified and summarized as:

If your initial guess is the car (chance 1/3) then you shouldn't switch, otherwise you should (and you will win).

To see that this is the case you can write down all possibilities or you can do what I did: a Monte Carlo simulation.

Monte Carlo in PHP

A Monte Carlo simulation is where you execute a probability experiment many times using a random number generator to determine the chances of winning. Here is the code written in PHP:

<?php
// function to determine win on monty hall problem
function monty_hall(array $doors, string $winner, string $chosen, bool $change): bool
{
    while (true) {
        // choose a random door to open
        $open = $doors[array_rand($doors)];
        // if door is not winning and not chosen open it
        if ($open != $winner && $open != $chosen) {
            break;
        }
    }
    // remove the open door from the array
    $doors = array_diff($doors, [$open]);
    // do you want to change?
    if ($change) {
        // remove the chosen door
        $doors = array_diff($doors, [$chosen]);
        // choose another door
        $chosen = $doors[array_rand($doors)];
    }
    return $chosen == $winner;
}
// monte carlo simulation to determine win chance of monty hall problem
$runs = 100000;
$wins = 0;
for ($i = 0; $i < $runs; $i++) {
    // doors is an array of closed doors
    $doors = ["Door 1", "Door 2", "Door 3"];
    // choose a random winning door
    $winner = $doors[array_rand($doors)];
    // choose a random door to open
    $chosen = $doors[array_rand($doors)];
    // increment win count on win
    if (monty_hall($doors, $winner, $chosen, true)) {
        $wins += 1;
    }
}
echo round(100 * $wins / $runs) . "%\n";

See: https://github.com/mevdschee/monty-hall-problem

Happy coding!

Links


PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.