Skip to content

Instantly share code, notes, and snippets.

@OddEssay
Created November 11, 2013 14:54
Show Gist options
  • Save OddEssay/7414331 to your computer and use it in GitHub Desktop.
Save OddEssay/7414331 to your computer and use it in GitHub Desktop.
Testing the numbers for the Monty Hall, Goat Behind Door Problem
<?php
function selectDoorPrizeIsBehind(){
return rand(1,3);
}
function selectDoorToOpen(){
return rand(1,3);
}
/**
* Off the none-prize doors, reveal a goat behind it.
* @param $prizeDoor
*
* @return int
*/
function revealGoat($prizeDoor,$doorToOpen){
$allDoors = array(
1 => 1,
2 => 2,
3 => 3
);
unset($allDoors[$prizeDoor]); // Don't reveal the prize door
if($prizeDoor != $doorToOpen) {
unset($allDoors[$doorToOpen]);
} // Don't show behind the selected door either (If it's a different door to the prize door)
return $allDoors[array_rand($allDoors)];
}
/**
* When we stick, then if the two doors match, we win.
* @param $prizeDoor
* @param $doorToOpen
*
* @return bool
*/
function stickWithDoor($prizeDoor,$doorToOpen){
if($prizeDoor == $doorToOpen){
return true;
} else {
return false;
}
}
/**
* In this case, we do the opposite
* @param $prizeDoor
* @param $doorToOpen
*
* @return bool
*/
function openOtherDoor($prizeDoor,$doorToOpen){
if($prizeDoor == $doorToOpen){
return false;
} else {
return true;
}
}
$c = 0;
$stickWins = 0;
$changeWins = 0;
while($c < 1000000){
$prizeDoor = selectDoorPrizeIsBehind();
//echo 'Prize is behind door: ' . $prizeDoor;
$doorToOpen = selectDoorToOpen();
//echo ' Picking door: ' . $doorToOpen;
$theGoatIsBehind = revealGoat($prizeDoor,$doorToOpen);
//echo ' Revaling a goat behind door: ' . $theGoatIsBehind;
if(stickWithDoor($prizeDoor,$doorToOpen)){
// echo ' Sticking You Win ';
$stickWins++;
}
if(openOtherDoor($prizeDoor,$doorToOpen)) {
// echo ' Changing You Win ';
$changeWins++;
}
//echo "\n";
++$c;
}
echo 'Out of '.$c.' games, sticking you win ' . $stickWins . ' but changing you win ' . $changeWins .' times.';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment