Last active
August 25, 2019 21:08
-
-
Save shuhei/d240082a9038f4ca3684d338b98ac1ef to your computer and use it in GitHub Desktop.
Monty Hall Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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