-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMontyHall.ts
64 lines (55 loc) · 2.01 KB
/
MontyHall.ts
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
/**
* MontyHall.ts
*
* Example Monty Hall problem simulation.
* usage: ts-node MontyHall.ts
*
* @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)
const numberOfRuns: number = 1000000;
let keepWins: number = 0;
let keepLosses: number = 0;
let changeWins: number = 0;
let changeLosses: number = 0;
// loop numberOfRuns without changing our initial door selection
for (let i: number = 0; i < numberOfRuns; i++) {
// pick a winning door between 1 and 3
const winningDoor: number = Math.floor(Math.random() * 3) + 1;
// player selects a random door between 1 and 3
const playerDoor: number = Math.floor(Math.random() * 3) + 1;
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 (let i: number = 0; i < numberOfRuns; i++) {
// pick a winning door between 1 and 3
const winningDoor: number = Math.floor(Math.random() * 3) + 1;
// player selects a random door between 1 and 3
const playerDoor: number = Math.floor(Math.random() * 3) + 1;
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++;
}
}
console.log(`Keep Wins/Losses: ${keepWins}/${keepLosses} (${(keepWins / numberOfRuns) * 100}% wins)`);
console.log(`Change Wins/Losses: ${changeWins}/${changeLosses} (${(changeWins / numberOfRuns) * 100}% wins)`);