Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active August 25, 2019 21:08
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 shuhei/d240082a9038f4ca3684d338b98ac1ef to your computer and use it in GitHub Desktop.
Save shuhei/d240082a9038f4ca3684d338b98ac1ef to your computer and use it in GitHub Desktop.
Monty Hall Problem
const doors = [0, 1, 2];
const tries = 100000;
let pickHasCar = 0;
let theOtherHasCar = 0;
for (let i = 0; i < tries; i++) {
const car = doors[random(3)];
const pick = doors[random(3)];
// Open a door that doesn't have the car.
const open =
pick === car
? doors.filter(d => d !== pick)[random(2)]
: doors.find(d => d !== pick && d !== car);
const theOther = doors.find(d => d !== pick && d !== open);
if (pick === car) {
pickHasCar++;
}
if (theOther === car) {
theOtherHasCar++;
}
}
console.log({
pickHasCar,
theOtherHasCar,
ratio: theOtherHasCar / pickHasCar
});
function random(upperBound) {
return Math.floor(upperBound * Math.random());
}
// When the pick has the car (1/3), the other one doesn't have the car for sure.
// When the pick doesn't have the car (2/3), the other one has the car for sure.
// So, the other one has the car by 2/3 chance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment