Last active
November 26, 2016 11:54
-
-
Save shiny/3760c4ca244e9efbd5d087f5757e5091 to your computer and use it in GitHub Desktop.
三门问题 PHP 模拟代码
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 | |
define('GOAT', 0); | |
define('CAR', 1); | |
echo "尝试五次,每次1000遍,换门的中奖率\n"; | |
for($j=0;$j<5;$j++) { | |
$exchange = true; | |
simulation($exchange); | |
} | |
echo "\n再尝试五次,每次1000遍,不换门的中奖率\n"; | |
for($j=0;$j<5;$j++) { | |
$exchange = false; | |
simulation($exchange); | |
} | |
//运行模拟,每次模拟运行1000次 | |
function simulation($exchange) | |
{ | |
$pool = []; | |
for($i=0; $i<1000; $i++) { | |
$pool[$i] = start($exchange); | |
} | |
//过滤掉山羊 | |
$cars = array_filter($pool); | |
$total = count($pool); | |
$car_total = count($cars); | |
echo sprintf("%.2f%%\n", ($car_total / $total) * 100); | |
} | |
//节目开始 | |
function start($exchange) | |
{ | |
//有三扇门 | |
$doors = generate_doors(); | |
//随机选中一扇 | |
$choose_pos = choose_door(); | |
//主持人打开有山羊的一扇 | |
$open_pos = open_door($doors, $choose_pos); | |
//换吗? | |
if($exchange) { | |
//换:找到最后一扇门 | |
$diff = array_diff([0, 1, 2], [$choose_pos, $open_pos]); | |
$last_door_pos = array_shift($diff); | |
} else { | |
//不换 | |
$last_door_pos = $choose_pos; | |
} | |
if($doors[$last_door_pos]==GOAT) { | |
//没中奖 | |
return false; | |
} else { | |
//中奖了 | |
return true; | |
} | |
} | |
function generate_doors() | |
{ | |
//0 是山羊 | |
//1 是汽车 | |
$pos = mt_rand(0, 2); | |
//在所有门里放满羊 | |
$doors = [GOAT, GOAT, GOAT]; | |
//然后把其中一扇门里的羊改成汽车 | |
$doors[$pos] = CAR; | |
return $doors; | |
} | |
function choose_door() | |
{ | |
return mt_rand(0, 2); | |
} | |
function open_door($doors, $choose_pos) | |
{ | |
$doors[$choose_pos] = -1; | |
//找到剩下的山羊 | |
return array_search(GOAT, $doors); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment