Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@drkibitz
Last active June 6, 2023 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drkibitz/2f5e0340175ba81c5f22fef5cdf4b287 to your computer and use it in GitHub Desktop.
Save drkibitz/2f5e0340175ba81c5f22fef5cdf4b287 to your computer and use it in GitHub Desktop.
Monty Hall Problem
/**
* The Monty Hall Problem
* https://en.wikipedia.org/wiki/Monty_Hall_problem
*/
// convert 0.333 to 33%
const toPercentInteger = (fraction) => {
return Math.floor(fraction * 100);
};
// Get faction (0-1) chance of winning out of total games
const montyHallSamples = (numberOfDoors = 3, switchChoice = false, totalGames = 1) => {
// Single game, returns true for win, false for loss
const singleGame = () => {
const prize = Math.floor(Math.random() * numberOfDoors);
const choice = Math.floor(Math.random() * numberOfDoors);
return (choice != prize) ? switchChoice : !switchChoice;
};
// Get total wins from total games
const totalWins = (totalGames) => {
let wins = 0;
while (totalGames--) {
if (singleGame()) wins += 1;
}
return wins;
};
return totalWins(totalGames) / totalGames;
};
// Logs info about the sample
const logSamples = (numberOfDoors = 3, totalGames = 10000000) => {
console.log(
`With ${numberOfDoors} doors,`,
`switching has a ${toPercentInteger(montyHallSamples(numberOfDoors, true, totalGames))}% chance of winning,`,
`while not switching has a ${toPercentInteger(montyHallSamples(numberOfDoors, false, totalGames))}% chance.`,
);
};
// BEGIN SAMPLING
/**
* Assert this, because this is actually pretty acurate with this many samples ;)
*/
console.assert(
toPercentInteger(montyHallSamples(3, true, 10000000)) == toPercentInteger(2 / 3),
'There should be a 2/3 chance of winning by switching!',
);
console.assert(
toPercentInteger(montyHallSamples(3, false, 10000000)) == toPercentInteger(1 / 3),
'There should be a 1/3 chance of winning by not switching!',
);
logSamples(3);
/**
* Change the number of doors simulating the game where the same rules apply,
* except the host opens all the doors except the door you chose plus one.
* By increasing the number of doors:
* - Chance of winning increases by switching
* - Chance of winning decreases by not switching
*/
logSamples(4);
logSamples(6);
logSamples(50);
/**
* Lastly, try changing the number of doors to 2.
* The only case that switching does not matter (with more than 1 door).
*/
logSamples(2);
// The end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment