Last active
July 27, 2019 23:48
-
-
Save jsejcksn/625f70689c580e66365c1680df34fcbf 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
#!/usr/bin/env node | |
'use strict'; | |
function makeADeal (changeDoor, initialDoorNumber) { | |
if (initialDoorNumber && (initialDoorNumber < 1 || initialDoorNumber > 3)) | |
throw new Error('If provided, the inital door number must be 1, 2, or 3.'); | |
function randomInt (max = 1, min = 0) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
const lose = 'goat'; | |
const win = 'car'; | |
const doors = new Array(3).fill(lose); | |
doors[randomInt(doors.length - 1)] = win; | |
const selection = initialDoorNumber | |
? initialDoorNumber - 1 | |
: randomInt(doors.length - 1); | |
if (!changeDoor) | |
return { | |
doors, | |
result: doors[selection], | |
win: doors[selection] === win, | |
}; | |
const remaining = [...doors]; | |
remaining.splice(selection, 1); | |
for (const [index, door] of remaining.entries()) { | |
if (door === lose) { | |
remaining.splice(index, 1); | |
break; | |
} | |
} | |
const result = remaining.pop(); | |
return {doors, result, win: result === win}; | |
} | |
function simulate (iterations, changeDoor, initialDoorNumber) { | |
let wins = 0; | |
let losses = 0; | |
for (let i = 0; i < iterations; i++) { | |
makeADeal(changeDoor, initialDoorNumber).win ? wins++ : losses++; | |
} | |
return { | |
iterations, | |
losses, | |
wins, | |
win_percentage: 100 * (wins / iterations), | |
changed: changeDoor ? true : false, | |
}; | |
} | |
const one = makeADeal(true, 2); | |
const many = simulate(1000, true); | |
console.log({one, many}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment