Skip to content

Instantly share code, notes, and snippets.

@jsejcksn
Last active July 27, 2019 23:48
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 jsejcksn/625f70689c580e66365c1680df34fcbf to your computer and use it in GitHub Desktop.
Save jsejcksn/625f70689c580e66365c1680df34fcbf to your computer and use it in GitHub Desktop.
Monty Hall problem: Simulation
#!/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