Skip to content

Instantly share code, notes, and snippets.

@shuhei

shuhei/monty-hall.js

Last active Aug 25, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.