Skip to content

Instantly share code, notes, and snippets.

@matthayter
Created February 17, 2016 19:05
Show Gist options
  • Save matthayter/15496f6c5d1b4798c352 to your computer and use it in GitHub Desktop.
Save matthayter/15496f6c5d1b4798c352 to your computer and use it in GitHub Desktop.
A demonstration of the Monty Hall problem.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var monty = function(doSwitch) {
var tryCount = 10000;
var winCount = 0.0;
for (var i = 0; i < tryCount; i++) {
var car = getRandomInt(0, 3);
var choice = getRandomInt(0, 3);
console.log("Your choice: " + choice);
var openDoor = 0;
while (openDoor === choice || openDoor === car) {
openDoor += 1;
}
console.log("Open door: " + openDoor);
if (doSwitch) {
choice = 1 ^ 2 ^ choice ^ openDoor;
}
console.log("Car door: " + car);
console.log("Correct? " + (car == choice));
if (car === choice) {
winCount += 1;
}
}
return winCount / tryCount;
}
console.log("Win ratio: " + monty(true));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment