Skip to content

Instantly share code, notes, and snippets.

@freeall

freeall/monty-hall.js

Last active Mar 6, 2020
Embed
What would you like to do?
Super naive way of testing out the Monty Hall problem
/*
A quick stab at writing the Monty Hall problem, and testing out if it does indeed
give a 1/3 chance if you don't change the doors, but a 2/3 chance if you do.
https://en.wikipedia.org/wiki/Monty_Hall_problem
Running this, unsurprisingly, gives something like:
No change: 100000 runs. 33229 correct guesses. 33.23% correct
Change: 100000 runs. 66631 correct guesses. 66.63% correct
*/
const runs = 100000
const correctGuessesNoChange = run(montyHallNoChange, runs)
const correctGuessesChange = run(montyHallChange, runs)
console.log(`No change: ${runs} runs. ${correctGuessesNoChange} correct guesses. ${(100 * correctGuessesNoChange / runs).toFixed(2)}% correct`)
console.log(`Change: ${runs} runs. ${correctGuessesChange} correct guesses. ${(100 * correctGuessesChange / runs).toFixed(2)}% correct`)
function montyHallNoChange () {
const arr = shuffle([0, 0, 1])
const guess = Math.floor(Math.random() * 3)
const isCorrect = arr[guess] === 1
return isCorrect
}
function montyHallChange () {
const arr = shuffle([0, 0, 1])
let guess = Math.floor(Math.random() * 3)
const is0Goat = arr[0] === 0
const is1Goat = arr[1] === 0
const is2Goat = arr[2] === 0
const wouldGuessHaveBeenCorrect = arr[guess] === 1
if (wouldGuessHaveBeenCorrect) {
const chooseLeftmostDoor = Math.random() < 0.5
if (guess === 0 && chooseLeftmostDoor) guess = 1
else if (guess === 0 && !chooseLeftmostDoor) guess = 2
else if (guess === 1 && chooseLeftmostDoor) guess = 0
else if (guess === 1 && !chooseLeftmostDoor) guess = 2
else if (guess === 2 && chooseLeftmostDoor) guess = 0
else if (guess === 2 && !chooseLeftmostDoor) guess = 1
}
if (!wouldGuessHaveBeenCorrect) {
if (guess === 0 && is1Goat) guess = 2
else if (guess === 0 && is2Goat) guess = 1
else if (guess === 1 && is0Goat) guess = 2
else if (guess === 1 && is2Goat) guess = 0
else if (guess === 2 && is0Goat) guess = 1
else if (guess === 2 && is1Goat) guess = 0
}
const isCorrect = arr[guess] === 1
return isCorrect
}
function run (f, runs) {
let correctGuesses = 0
for (let i = 0; i < runs; i++) {
const isCorrectGuess = f()
if (isCorrectGuess) correctGuesses++
}
return correctGuesses
}
function shuffle (arr) {
// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]
}
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.