Skip to content

Instantly share code, notes, and snippets.

@CalvinCarmack
Created September 15, 2013 01:08
Show Gist options
  • Save CalvinCarmack/6567198 to your computer and use it in GitHub Desktop.
Save CalvinCarmack/6567198 to your computer and use it in GitHub Desktop.
Monty Hall problem
<?php
function play($strategy, $games = 10) {
$wins = 0;
for ($x = 0; $x < $games; $x++) {
$car = rand(0, 2);
$choice = rand(0, 2);
$closed = array(0, 1, 2);
if ($car == $choice) {
unset($closed[$choice]);
$closed = array_values($closed);
$closed = $closed[rand(0,1)];
} else {
$closed = $car;
}
if (
$strategy == 'switch' ||
($strategy == 'random' && rand(0,1))
) {
$choice = $closed;
}
if ($car == $choice) {
$wins++;
}
}
echo "$wins/$games ",$wins/$games, " $strategy", PHP_EOL;
}
$games = 1000000;
play('stay', $games);
play('switch', $games);
play('random', $games);
// $ php montyhall.php
// 333389/1000000 0.333389 stay
// 666774/1000000 0.666774 switch
// 499988/1000000 0.499988 random
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment