Skip to content

Commit d377d7c

Browse files
committed
Chapter 03 section 07 codes added.
1 parent 4081ed4 commit d377d7c

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

03-Probability-Simulation/06-Three-Gates-Problem/src/ThreeGatesExperiment.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public void run(boolean changeDoor){
1818
if(play(changeDoor))
1919
wins ++;
2020
System.out.println(changeDoor ? "Change" : "Not Change");
21-
System.out.println("win rate:" + (double)wins/N);
21+
System.out.println("winning rate:" + (double)wins/N);
2222
}
2323

2424
private boolean play(boolean changeDoor){
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
public class WinningPrize {
3+
4+
private double chance;
5+
private int playTime;
6+
private int N;
7+
8+
public WinningPrize(double chance, int playTime, int N){
9+
10+
if(chance < 0.0 || chance > 1.0)
11+
throw new IllegalArgumentException("chance must be between 0 and 1!");
12+
13+
if(playTime <= 0 || N <= 0)
14+
throw new IllegalArgumentException("playTime or N must be larger than 0!");
15+
16+
this.chance = chance;
17+
this.playTime = playTime;
18+
this.N = N;
19+
}
20+
21+
public void run(){
22+
23+
int wins = 0;
24+
for(int i = 0 ; i < N ; i ++)
25+
if(play())
26+
wins ++;
27+
28+
System.out.println("winning rate:" + (double)wins/N);
29+
}
30+
31+
public boolean play(){
32+
for(int i = 0 ; i < playTime ; i ++)
33+
if(Math.random() < chance)
34+
return true;
35+
return false;
36+
}
37+
38+
public static void main(String[] args) {
39+
40+
double chance = 0.2;
41+
int playTime = 5;
42+
int N = 1000000;
43+
44+
WinningPrize exp = new WinningPrize(chance, playTime, N);
45+
exp.run();
46+
}
47+
}

0 commit comments

Comments
 (0)