Created
August 4, 2018 16:49
-
-
Save lxe/2ce50ad115d4897c406a8f4e2eebedc8 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
This file contains hidden or 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 winsIfSwitched = []; | |
const winsIfStayed = []; | |
function monty () { | |
const doorWithCar = Math.floor(Math.random() * 3); | |
const guessedDoor = Math.floor(Math.random() * 3); | |
// Host removes a door that... | |
const removedDoor = [0,0,0].reduce((result, n, index) => { | |
// 1) contestant didn't pick and... | |
if (index === guessedDoor) return result; | |
// 2) doesn't have a car | |
if (index === doorWithCar) return result; | |
return index; | |
}, -1); | |
// Contestant has a choice to switch tho a door that... | |
const remainingDoor = [0,0,0].reduce((result, n, index) => { | |
// 1) contestant didn't already pick and... | |
if (index === guessedDoor) return result; | |
// 2) hasn't been removed by host | |
if (index === removedDoor) return result; | |
return index; | |
}, -1); | |
// Did contestant win if they stayed with the original guess? | |
const stayedResult = guessedDoor === doorWithCar; | |
// Did contestant win if they switched to the remaining door? | |
const switchedResult = remainingDoor === doorWithCar; | |
winsIfStayed.push(stayedResult); | |
winsIfSwitched.push(switchedResult); | |
} | |
const numTrials = 10000000; | |
console.log(`Running ${numTrials} trials...`); | |
for (i = 0; i < numTrials; i++) monty(); | |
console.log('Win rate if stayed', winsIfStayed.filter(Boolean).length / winsIfStayed.length); | |
console.log('Win rate if switched', winsIfSwitched.filter(Boolean).length / winsIfSwitched.length); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment