Skip to content

Instantly share code, notes, and snippets.

@skhavari
Created June 5, 2022 18:01
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 skhavari/145d130768ee52a51d0b26dc810c4bea to your computer and use it in GitHub Desktop.
Save skhavari/145d130768ee52a51d0b26dc810c4bea to your computer and use it in GitHub Desktop.
proving to the kids you should always switch doors....
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const setRemove = (list, r1, r2) => {
let temp = new Set(list);
temp.delete(r1);
temp.delete(r2);
return [...temp];
};
const GOAT = '🐐';
const PRIZE = '🚗';
const playGame = (shouldSwitch) => {
let doors = new Array(3).fill(GOAT);
let prize = rand(0, 2);
doors[prize] = PRIZE;
let contestantsChoice = rand(0, 2);
let removeChoices = setRemove([0, 1, 2], contestantsChoice, prize);
let removed = removeChoices[rand(0, removeChoices.length - 1)];
shouldSwitch = shouldSwitch === undefined ? (rand(0, 1) > 0.5 ? true : false) : shouldSwitch;
if (shouldSwitch) {
contestantsChoice = setRemove([0, 1, 2], contestantsChoice, removed)[0];
}
return contestantsChoice === prize;
};
const run = (switchStrategy) => {
let wins = 0;
const games = 100000;
for (let i = 0; i < games; i++) {
wins = playGame(switchStrategy) ? wins + 1 : wins;
}
return { games, wins, pct: Math.round((wins / games) * 100) };
};
let res = run(true);
console.log(`ALWAYS: Games: ${res.games}, Wins: ${res.wins}, Win %: ${res.pct}%`);
res = run(false);
console.log(`NEVER : Games: ${res.games}, Wins: ${res.wins}, Win %: ${res.pct}%`);
res = run();
console.log(`RANDOM: Games: ${res.games}, Wins: ${res.wins}, Win %: ${res.pct}%`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment