const ROOMS = ["goat", "goat", "car"];
function shuffle(array) {
const newArr = [...array];
for (let i = newArr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[j]] = [newArr[j], newArr[i]];
}
return newArr;
}
/**
* @param {boolean} shouldSwitch - Does the player switch?
* @param {boolean} isHostRandom - Does the host pick randomly (might show car)?
*/
function game(shouldSwitch, isHostRandom) {
const rooms = shuffle(ROOMS);
// 1. Player's initial choice
const playerChoiceIndex = Math.floor(Math.random() * rooms.length);
// 2. Host's choice
// Get all indices EXCEPT the player's choice
const possibleHostIndices = [0, 1, 2].filter(i => i !== playerChoiceIndex);
let hostOpensIndex;
if (isHostRandom) {
// Host picks any remaining door completely at random
hostOpensIndex = possibleHostIndices[Math.floor(Math.random() * possibleHostIndices.length)];
} else {
// Standard Monty Hall: Host MUST pick a goat
const goatIndices = possibleHostIndices.filter(i => rooms[i] === "goat");
hostOpensIndex = goatIndices[Math.floor(Math.random() * goatIndices.length)];
}
// 3. Check for "Monty Fall" disaster
// If the host accidentally reveals the car, the game ends (player loses/void)
if (rooms[hostOpensIndex] === "car") {
return false;
}
// 4. Final Result
if (shouldSwitch) {
const finalChoiceIndex = [0, 1, 2].find(i => i !== playerChoiceIndex && i !== hostOpensIndex);
return rooms[finalChoiceIndex] === "car";
} else {
return rooms[playerChoiceIndex] === "car";
}
}
// --- Simulation Results ---
const trials = 100000;
let randomHostSwitch = 0;
let randomHostKeep = 0;
let smartHostSwitch = 0;
let smartHostKeep = 0;
for (let i = 0; i < trials; i++) {
if (game(true, true)) randomHostSwitch++;
}
for (let i = 0; i < trials; i++) {
if (game(false, true)) randomHostKeep++;
}
for (let i = 0; i < trials; i++) {
if (game(true, false)) smartHostSwitch++;
}
for (let i = 0; i < trials; i++) {
if (game(false, false)) smartHostKeep++;
}
console.log(`Random Host Switch Win Rate: ${(randomHostSwitch / trials * 100).toFixed(2)}%`);
console.log(`Random Host Keep Win Rate: ${(randomHostKeep / trials * 100).toFixed(2)}%`);
console.log(`Smart Host Switch Win Rate: ${(smartHostSwitch / trials * 100).toFixed(2)}%`);
console.log(`Smart Host Keep Win Rate: ${(smartHostKeep / trials * 100).toFixed(2)}%`);