Monty Hall Problem in PHP

November 23, 2016
define('HAS_PRICE', true);
define('HAS_NO_PRICE', false);
$tries    = 0;
$won      = 0;
$wonFirst = 0;
$i        = 0;
$pick     = 0;

/**
 * Bottom line, you play against being wrong the first time
 */
while (++$i <= 100000) {
    $scenario = [HAS_NO_PRICE, HAS_NO_PRICE, HAS_NO_PRICE];
    /**
     * Set random scenario element to true
     */
    $scenario[mt_rand(0, 2)] = HAS_PRICE;

    /**
     * First pick - 1 in 3
     */
    $pick = mt_rand(0, 2);
    if ($scenario[$pick] === HAS_PRICE) {
        $wonFirst++;
    } else {
        $won++;
    }

    $tries++;
}

echo 'Won: ' . $won . ' from ' . $tries . ' = ' . ($won / $tries) . '% and first pick won ' . $wonFirst . ' ' . ($wonFirst / $tries) . '%' . PHP_EOL;

Won: 66780 from 100000 = 0.6678% and first pick won 33220 0.3322%

tags: , ,
posted in php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org