Skip to content

Instantly share code, notes, and snippets.

@xavieryao
Created October 2, 2013 05:35
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 xavieryao/6789509 to your computer and use it in GitHub Desktop.
Save xavieryao/6789509 to your computer and use it in GitHub Desktop.
Programming implementation of Monty Hall Problem.
/*
* Programming implementation of Monty Hall Problem.
* By Prof.X (http://weibo.com/xavieryao)
*/
//Variants to store experiment time and result.
var time = 0.0;
var changeAndWin = 0.0;
var winWithoutChange = 0.0;
while(true){
/*
* There are three doors, Door 0,1,2.
*/
var doors = new Array();
/*
* Behind one of them there hides an award.
*/
var doorWithAward = parseInt(3*Math.random());
doors[doorWithAward] = 'Award';
var emptyDoors;
switch(doorWithAward){
case 0:
emptyDoors = [1,2];
break;
case 1:
emptyDoors = [0,2];
break;
case 2:
emptyDoors = [0,1];
}
/*
* Pick one of the doors.
*/
var pickedDoor = parseInt(3*Math.random());
/*
* Open an empty door.
*/
var openedDoor;
if(pickedDoor == doorWithAward){
openedDoor = emptyDoors[parseInt(2*Math.random())];
}else{
openedDoor = 3 - doorWithAward - pickedDoor;
}
/*
* Change selection.
*/
var changed = false;
if(Math.random()<0.5){
pickedDoor = 3 - openedDoor - pickedDoor;
changed = true;
}
/*
* Open the door.
*/
if(doors[pickedDoor]=='Award'){
if(changed){
changeAndWin ++;
}else{
winWithoutChange ++;
}
}
time++;
console.log('第'+time+'次实验,更换门且获胜的频率为:'+changeAndWin/time+' 未更换获胜的频率为:'+winWithoutChange/time+ ' 更换后获胜的频率是更换前的'+changeAndWin/winWithoutChange+'倍');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment