Skip to content

Instantly share code, notes, and snippets.

@CalvinCarmack
Last active December 23, 2015 02:29
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 CalvinCarmack/6567168 to your computer and use it in GitHub Desktop.
Save CalvinCarmack/6567168 to your computer and use it in GitHub Desktop.
Two Envelopes
<?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