Skip to content

Instantly share code, notes, and snippets.

@dlmanning
Last active Jun 19, 2017
Embed
What would you like to do?
Simulation of the Monty Hall problem
/*
There are a certain number of doors (usually 3). Behind one is a prize. Behind the others are goats.
The contestant picks a door, and then the host removes one of the non-selected choices that did contain
the prize. The contestant is given the option to either keep their original choice, or switch to one of
the remaining doors. What should they do?
Let's simulate their potential decisions to find out!
*/
const doors = [1, 2, 3]
const numberOfTrials = 100000
const resultsForSwitching = {
WIN: 0,
LOSE: 0
}
const resultsForStaying = {
WIN: 0,
LOSE: 0
}
console.log(`Running ${numberOfTrials} simulations of Monty Hall problem with ${doors.length} doors\n`)
for (let i = 0; i < numberOfTrials; i++) {
resultsForStaying[playGameWithStrategy('STAY')]++
resultsForSwitching[playGameWithStrategy('SWITCH')]++
}
console.log(`Results when switching: ${formatResults(resultsForSwitching)}`)
console.log(`Results when keeping original choice: ${formatResults(resultsForStaying)}`)
function playGameWithStrategy (strategy) {
const prizeBehind = pick(...doors) // Hide the prize behind a door
const firstChoice = pick(...doors) // Contestant picks a door
// host removes one of the doors the contestant did not select that does not contain the prize
const removed = pick(...doors.filter(choice => choice !== firstChoice && choice !== prizeBehind))
// based on selected strategy, the contestant will either keep their original choice, or pick the remaining door
const finalChoice = strategy === 'SWITCH'
? pick(...doors.filter(choice => choice !== firstChoice && choice !== removed))
: firstChoice
return finalChoice === prizeBehind ? 'WIN' : 'LOSE'
}
function pick (...choices) {
const numberOfChoices = choices.length
const choiceIndex = Math.floor(Math.random() * numberOfChoices)
return choices[choiceIndex]
}
function formatResults (results) {
return `
Wins: ${results.WIN}
Loses: ${results.LOSE}
Winning percentage: ${100 * results.WIN / (results.WIN + results.LOSE)}%
`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment