Skip to content

Instantly share code, notes, and snippets.

@promatik
Created April 7, 2015 14:32
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 promatik/a18952e2c5c08a620fdd to your computer and use it in GitHub Desktop.
Save promatik/a18952e2c5c08a620fdd to your computer and use it in GitHub Desktop.
Monty Hall Simulation
function montyhallSimulation(playerChangeOpt, testcases)
{
playerChangeOpt = typeof playerChangeOpt !== 'undefined' ? playerChangeOpt : true;
testcases = typeof testcases !== 'undefined' ? testcases : 100;
var right = 0, wrong = 0;
for(i=0 ; i<testcases ; i++) {
var carPos = Math.floor(Math.random()*3);
var playerOpt = Math.floor(Math.random()*3);
var firstGoat;
while(firstGoat == undefined || firstGoat == carPos || firstGoat == playerOpt)
firstGoat = Math.floor(Math.random()*3);
if(playerChangeOpt) {
var newOpt;
while(newOpt == undefined || newOpt == firstGoat || newOpt == playerOpt)
newOpt = Math.floor(Math.random()*3);
playerOpt = newOpt;
}
carPos == playerOpt ? right++ : wrong++;
}
console.log("Winning: " + right*100/testcases + "%");
console.log("Loses: " + wrong*100/testcases + "%");
}
// Player change his choice, 100 testcases
montyhallSimulation();
// Player change his choice, 1k testcases
montyhallSimulation(true, 1000);
// Player do not change his choice, 1k testcases
montyhallSimulation(false, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment