Created
November 18, 2013 01:23
-
-
Save robsears/7520898 to your computer and use it in GitHub Desktop.
Monty Hall Program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This program simulates a number of games involving | |
// The Monty Hall Problem, and compares two approaches: | |
// sticking with the player's original choice, or | |
// switching to the other option. The program measures | |
// how successful each approach is and prints the | |
// result to the screen. I used PHP since it is easy to | |
// read and understand, but this program could easily | |
// be ported to any number of other languages. | |
// Set the number of trials to be performed for | |
// each option (stick or switch). More trials | |
// will lead to better accuracy, but increased | |
// computing time. 1 million seems to work well: | |
$trials = 1000000; | |
//--------- EDIT BELOW AT YOUR OWN RISK:--------------// | |
$choices = array('stick', 'switch'); | |
$wins_stick = 0; | |
$wins_switch = 0; | |
$options = array('A', 'B', 'C'); | |
foreach ($choices as $choice) { | |
for ($i=0; $i<$trials; $i++) { | |
// Random door has big prize: | |
$correct = $options[rand(0,2)]; | |
// Contestant picks random door: | |
$contestant_pick = $options[rand(0,2)]; | |
// Figure out Monty's choice of doors to reveal: | |
$montys_picks = array(); | |
foreach ($options as $option) { | |
if ($option != $correct && $option != $contestant_pick) { | |
array_push($montys_picks, $option); | |
} | |
} | |
// Monty picks a door that doesn't have the prize | |
// AND that the contestant hasn't chosen: | |
$montys_pick = (count($montys_picks) > 1) ? $montys_picks[rand(0,1)] : $montys_picks[0]; | |
// Increment if contestant sticks with door and is correct | |
if ($choice == 'stick' && $contestant_pick == $correct) { | |
$wins_stick++; | |
} | |
// Increment if contestant switches with door and is correct | |
if ($choice == 'switch' && $contestant_pick != $correct) { | |
$wins_switch++; | |
} | |
} | |
} | |
// Print results: | |
print "Contestant stuck by and won the car " . (round(($wins_stick*100/$trials),1)) . "% of the time (based on " . number_format($trials) . " trials).<br />"; | |
print "Contestant switched and won the car " . (round(($wins_switch*100/$trials),1)) . "% of the time (based on " . number_format($trials) . " trials).<br />"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment