And here is the code so simulate the Monty Hall problem for an arbitrary number of doors:
function montyHallSimulation(doorNum, runs) {
// Track the results
var wins = 0;
var losses = 0;
// Simulate the game
for (var i = 0; i < runs; i++) {
// Initialize the doors
var doors = new Array(doorNum);
doors.fill("x");
let chosenDoor = Math.floor(Math.random() * doors.length);
let carDoor = Math.floor(Math.random() * doors.length);
let montyDoor = -1;
doors[chosenDoor] = "chosen";
doors[carDoor] = "car";
// The player guessed correctly with their first pick!
if (chosenDoor === carDoor) {
doors[chosenDoor] = "chosen + car";
// We need to reveal some arbitrary door that isn't the
// same one the player has selected
do {
montyDoor = Math.floor(Math.random() * doors.length);
//console.log(`${montyDoor} is Monty's pick, and chosen is ${chosenDoor}`);
} while (montyDoor == chosenDoor);
doors[montyDoor] = "monty pick";
} else {
// Monty's pick will be the door the car is behind
montyDoor = carDoor;
doors[carDoor] = "car + monty pick";
}
//
// Tracking!
//
if (chosenDoor !== carDoor) {
// Switching caused a win
wins++;
} else {
// Switching caused a loss
losses++;
}
}
console.log(`${wins} are the wins and ${losses} are the losses!`);
console.log(`Switching resulted in a ${100 * (wins / runs)}% win rate!`);
console.log("------------------------");
}
montyHallSimulation(20, 10000);
This example uses 20 doors as in my example from the earlier article, and the win rate for switching is indeed around 95%