-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
55 lines (46 loc) · 1.76 KB
/
PercolationStats.java
File metadata and controls
55 lines (46 loc) · 1.76 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
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private double mean;
private double stddev;
private double T;
public PercolationStats(int N, int T, PercolationFactory pf) {
if (N <= 0 || T <= 0) {
throw new IllegalArgumentException();
}
this.T = T;
double[] ratio = new double[T];
for (int i = 0; i < T; i += 1) {
Percolation p = pf.make(N);
while (!p.percolates()) {
int randRow = StdRandom.uniform(N);
int randCol = StdRandom.uniform(N);
p.open(randRow, randCol);
}
ratio[i] = ((double) p.numberOfOpenSites()) / (N * N);
}
this.mean = StdStats.mean(ratio);
this.stddev = StdStats.stddev(ratio);
}
public double mean() {
return mean;
}
public double stddev() {
return stddev;
}
public double confidenceLow() {
return mean - 1.96 * stddev / Math.sqrt(T);
}
public double confidenceHigh() {
return mean + 1.96 * stddev / Math.sqrt(T);
}
public static void main(String[] args) {
int trials = 100, gridSize = 50;
PercolationFactory pf = new PercolationFactory();
PercolationStats ps = new PercolationStats(gridSize, trials, pf);
System.out.printf("Grid Size: %d x %d | Number of Trials: %d%n", gridSize, gridSize, trials);
System.out.printf("The mean percolation threshold is %.2f%n", ps.mean());
System.out.printf("The standard deviation of the percolation threshold is %.2f.%n", ps.stddev());
System.out.printf("The 95%% confidence interval is [%.3f, %.3f].%n", ps.confidenceLow(), ps.confidenceHigh());
}
}