-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
77 lines (65 loc) · 1.98 KB
/
Copy pathPercolationStats.java
File metadata and controls
77 lines (65 loc) · 1.98 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
65
66
67
68
69
70
71
72
73
74
75
76
77
package coursera;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private double[] thresholds;
private int trials;
private int size;
// perform T independent computational experiments on an N-by-N grid
public PercolationStats(int N, int T) {
if (N <= 0)
throw new java.lang.IllegalArgumentException("N is out of bounds");
if (T <= 0)
throw new java.lang.IllegalArgumentException("T is out of bounds");
this.size = N;
this.trials = T;
this.thresholds = new double[trials];
for (int i = 0; i < T; i++) {
thresholds[i] = findThreshold();
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(thresholds);
}
// sample standard deviation of percolation threshold
public double stddev() {
if (trials == 1)
return Double.NaN;
return StdStats.stddev(thresholds);
}
// returns lower bound of the 95% confidence interval
public double confidenceLo() {
return mean() - 1.96 * stddev() / Math.sqrt(trials);
}
// returns upper bound of the 95% confidence interval
public double confidenceHi() {
return mean() + 1.96 * stddev() / Math.sqrt(trials);
}
private double findThreshold() {
Percolation perc = new Percolation(size);
int i, j;
int count = 0;
while (!perc.percolates()) {
do {
i = StdRandom.uniform(size) + 1;
j = StdRandom.uniform(size) + 1;
} while (perc.isOpen(i, j));
count++;
perc.open(i, j);
perc.isFull(i,j);
System.out.println(count);
}
return count / (Math.pow(size, 2));
}
// test client, described below
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats stats = new PercolationStats(N, T);
StdOut.printf("mean = %f\n", stats.mean());
StdOut.printf("stddev = %f\n", stats.stddev());
StdOut.printf("95%% confidence interval = %f, %f\n", stats.confidenceLo(), stats.confidenceHi());
}
}