-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
64 lines (49 loc) · 1.82 KB
/
PercolationStats.java
File metadata and controls
64 lines (49 loc) · 1.82 KB
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
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private final int trials;
private final double[] fractions;
public PercolationStats(int n, int t) {
if (n <= 0 || t <= 0) {
throw new IllegalArgumentException("Given n <= 0 || t <= 0");
}
this.trials = t;
this.fractions = new double[t];
for (int i = 0; i < this.trials; i++) {
Percolation percolation = new Percolation(n);
int result = 0;
while (!percolation.percolates()) {
int row = StdRandom.uniform(1, n + 1);
int col = StdRandom.uniform(1, n + 1);
if (!percolation.isOpen(row, col)) {
percolation.open(row, col);
result++;
}
}
double fraction = (double) result / (double) (n * n);
fractions[i] = fraction;
}
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int t = Integer.parseInt(args[1]);
PercolationStats ps = new PercolationStats(n, t);
String confidence = ps.confidenceLo() + ", " + ps.confidenceHi();
StdOut.println("mean = " + ps.mean());
StdOut.println("stddev = " + ps.stddev());
StdOut.println("95% confidence interval = " + confidence);
}
public double mean() {
return StdStats.mean(fractions);
}
public double stddev() {
return StdStats.stddev(fractions);
}
public double confidenceLo() {
return mean() - (1.96 * stddev() / Math.sqrt(trials));
}
public double confidenceHi() {
return mean() + ((1.96 * stddev()) / Math.sqrt(trials));
}
}