-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMontyHall.php
65 lines (56 loc) · 1.84 KB
/
MontyHall.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
/**
* MontyHall.php
*
* Example Monty Hall problem simulation.
* usage: php MontyHall.php
*
* @author Maxamilian Demian
* @link https://www.maxodev.org
* @link https://github.com/Maxoplata/MontyHall
*/
// The number of times to run for each choice (keep and change will run numberOfRuns times EACH)
$numberOfRuns = 1000000;
$keepWins = 0;
$keepLosses = 0;
$changeWins = 0;
$changeLosses = 0;
// loop numberOfRuns without changing our initial door selection
for ($i = 0; $i < $numberOfRuns; $i++) {
// pick a winning door between 1 and 3
$winningDoor = rand(1, 3);
// player selects a random door between 1 and 3
$playerDoor = rand(1, 3);
if ($playerDoor === $winningDoor) {
// player chose the winning door
$keepWins++;
} else {
// player chose a losing door
$keepLosses++;
}
}
// loop numberOfRuns while changing our initial door selection
for ($i = 0; $i < $numberOfRuns; $i++) {
// pick a winning door between 1 and 3
$winningDoor = rand(1, 3);
// player selects a random door between 1 and 3
$playerDoor = rand(1, 3);
if ($playerDoor === $winningDoor) {
// player chose the winning door already, count it as a loss as the player will be changing
$changeLosses++;
} else {
/* if the player HAS NOT chosen the winning door already and they change, they will win
* example:
* - player chooses door 1
* - winning door is door 3
* - host opens door 2 showing a goat
* - player switches to door 3 and wins
*
* every variation of this will win since we have already eliminated the aspect of the player
* having already picked the winning door
*/
$changeWins++;
}
}
print "Keep Wins/Losses: {$keepWins}/{$keepLosses} (" . (($keepWins / $numberOfRuns) * 100) . "% wins)" . PHP_EOL;
print "Change Wins/Losses: {$changeWins}/{$changeLosses} (" . (($changeWins / $numberOfRuns) * 100) . "% wins)" . PHP_EOL;