Last active
February 7, 2020 13:05
-
-
Save leonardofreitass/17b429f3ef52a208fa762f768b6c74d4 to your computer and use it in GitHub Desktop.
Monty Hall Problem
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
// Amount of time to run the problem | |
const RUN_TIMES = 10000 | |
const runProblem = (change) => { | |
// Starts with 3 doors containing nothing | |
const chances = ['nothing', 'nothing', 'nothing'] | |
// Puts money behind one of the three doors randomly | |
chances[Math.floor(Math.random() * 3)] = 'money' | |
// Picks one of the doors randomly | |
const choice = Math.floor(Math.random() * 3); | |
// If choice should not change, returns the result with what is behind that door | |
if (!change) { | |
return chances[choice] | |
} | |
// Removes the door chosen | |
chances.splice(choice, 1) | |
// If there is still money behind one of the doors | |
// This is important, as the host always knows this, and will never open a door with money | |
if (chances.indexOf('money') > -1) { | |
// Remove the door without the money | |
chances.splice(chances.indexOf('nothing'), 1) | |
// Returns the result with what is behind the door left | |
return chances[0] | |
} | |
// If there is no money behind one of the doors, remove any door randomly | |
chances.splice(Math.floor(Math.random() * 2), 1) | |
// Returns the result with what is behind the door left | |
return chances[0] | |
} | |
const results = { | |
money: 0, | |
nothing: 0 | |
} | |
for (let x = 0; x < RUN_TIMES; x++) { | |
const choice = runProblem(true) | |
// Increments the on the results whatever came back | |
results[choice]++ | |
} | |
// Prints results | |
console.log(results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment