Last active
December 23, 2015 02:29
-
-
Save CalvinCarmack/6567168 to your computer and use it in GitHub Desktop.
Two Envelopes
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 | |
function play($switch, $games, $small) { | |
$wins = 0; | |
$winnings = 0; | |
for ($x = 0; $x < $games; $x++) { | |
//which envelop is double the amount | |
$double = rand(0, 1); | |
//which envelop is initally chosen | |
$choice = rand(0, 1); | |
//which envelop wasn't chosen (the other one) | |
if ($choice == 0) { | |
$other = 1; | |
} else { | |
$other = 0; | |
} | |
// switch if that's our strategy | |
if ($switch) { | |
$choice = $other; | |
} | |
// we'll always get at least the small amount | |
$winnings += $small; | |
// if we chose the double envelop we get twice the small amount | |
if ($double == $choice) { | |
$wins++; | |
$winnings += $small; | |
} | |
} | |
echo "$$winnings $wins/$games ",$wins/$games,' '; | |
echo $switch ? 'always' : 'never'; | |
echo ' switched', PHP_EOL; | |
} | |
$games = 1000000; | |
$small = 1; | |
play(false, $games, $small); | |
play(true, $games, $small); | |
// $ php envelopes.php | |
// $1500308 500308/1000000 0.500308 never switched | |
// $1500301 500301/1000000 0.500301 always switched |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment