-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathWinningPrize.java
47 lines (34 loc) · 1.07 KB
/
WinningPrize.java
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
public class WinningPrize {
private double chance;
private int playTime;
private int N;
public WinningPrize(double chance, int playTime, int N){
if(chance < 0.0 || chance > 1.0)
throw new IllegalArgumentException("chance must be between 0 and 1!");
if(playTime <= 0 || N <= 0)
throw new IllegalArgumentException("playTime or N must be larger than 0!");
this.chance = chance;
this.playTime = playTime;
this.N = N;
}
public void run(){
int wins = 0;
for(int i = 0 ; i < N ; i ++)
if(play())
wins ++;
System.out.println("winning rate: " + (double)wins/N);
}
private boolean play(){
for(int i = 0 ; i < playTime ; i ++)
if(Math.random() < chance)
return true;
return false;
}
public static void main(String[] args) {
double chance = 0.2;
int playTime = 5;
int N = 1000000;
WinningPrize exp = new WinningPrize(chance, playTime, N);
exp.run();
}
}