-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
63 lines (62 loc) · 2.12 KB
/
PercolationStats.java
File metadata and controls
63 lines (62 loc) · 2.12 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
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private final int t;
private final int n;
private double meanVal;
private double stddevVal;
private double[] testResults;
public PercolationStats(int enn, int trials) {
if (enn <= 0 || trials <= 0)throw new IllegalArgumentException("Out of Bounds!");
n = enn;
t = trials;
meanVal = 0.0d;
stddevVal = 0.0d;
testResults = new double[t];
}
private double test() {
Percolation p = new Percolation(n);
int i, j;
while (!p.percolates()) {
i = StdRandom.uniform(n) + 1;
j = StdRandom.uniform(n) + 1;
if (!p.isOpen(i, j)) p.open(i, j);
}
double ret = (p.numberOfOpenSites() / (double) (n * n));
return ret;
}
private void performTests() {
int i;
for (i = 0; i < t; i++) {
testResults[i] = test();
}
}
private double confidence(double m) {
if (meanVal == 0.0d) mean();
if (stddevVal == 0.0d) stddev();
return (meanVal + ((m * 1.96 * stddevVal) / Math.sqrt(t)));
}
// Public methods
public double mean() {
if (testResults[0] == 0.0d) performTests();
meanVal = StdStats.mean(testResults);
return meanVal;
}
public double stddev() {
if (testResults[0] == 0.0d) performTests();
stddevVal = StdStats.stddev(testResults);
return stddevVal;
}
public double confidenceLo() {
return confidence(-1);
}
public double confidenceHi() {
return confidence(1);
}
public static void main(String[] args) {
PercolationStats ps = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
System.out.println("mean = " + ps.mean());
System.out.println("stddev = " + ps.stddev());
System.out.println("95% confidence interval = [" + ps.confidenceLo() + ", " + ps.confidenceHi() + "]");
}
}