Skip to content

Instantly share code, notes, and snippets.

@jpreardon
Created March 20, 2016 13:31
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 jpreardon/ac97144518962776dda7 to your computer and use it in GitHub Desktop.
Save jpreardon/ac97144518962776dda7 to your computer and use it in GitHub Desktop.
// A crude simulation of Wait but why's Jellybean Problem
// http://waitbutwhy.com/2016/03/the-jellybean-problem.html
// This is the simulation:
// Randomly pick a number between 1 and 3 (this is the wining choice)
// Randomly pick a second number between 1 and 3 (this is the player's first choice)
// Compare the two numbers:
// - If they are the same, sticking to first choice will win, switchers will lose
// - If they are different, sicking to the first choice will lose, switchers will win
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var numSimulations = 300000
var currentSimulation = 1
var switchers = 0
var nonswitchers = 0
while (currentSimulation < numSimulations + 1) {
if (getRandomIntInclusive(1,3) == getRandomIntInclusive(1,3)) {
// Non-switchers win!
nonswitchers++
} else {
// Switchers win!
switchers++
}
currentSimulation++
}
console.log("Out of " + numSimulations + " simulations...")
console.log("If you didn't switch you won " + nonswitchers + " times (" + (nonswitchers/numSimulations * 100).toPrecision(2) + "%)")
console.log("If you switched you won " + switchers + " times (" + (switchers/numSimulations * 100).toPrecision(2) + "%)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment