-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
77 lines (59 loc) · 2.5 KB
/
PercolationStats.java
File metadata and controls
77 lines (59 loc) · 2.5 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 percolation;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private int numberOfTrials;
private Percolation percolation;
private double[] fractionNumberOfOpenSites;
// perform independent trials on an n-by-n grid
public PercolationStats(int n, int trials) {
if(n <= 0 || trials <= 0)
throw new IllegalArgumentException("n/trials cannot be less or equal to 0");
numberOfTrials = trials;
fractionNumberOfOpenSites = new double[trials];
int randomRowNumber;
int randomColNumber;
for(int i = 0; i < trials; i++) {
percolation = new Percolation(n);
while(!percolation.percolates()) {
randomRowNumber = StdRandom.uniformInt(1, n + 1);
randomColNumber = StdRandom.uniformInt(1, n + 1);
percolation.open(randomRowNumber, randomColNumber);
}
fractionNumberOfOpenSites[i] = percolation.numberOfOpenSites() / ((n * n) * 1.0);
percolation = null;
}
}
// sample mean of percolation threshold
public double mean() {
return StdStats.mean(fractionNumberOfOpenSites);
}
// sample standard deviation of percolation threshold
public double stddev() {
return StdStats.stddev(fractionNumberOfOpenSites);
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return (mean() - ((1.96 * stddev()) / Math.sqrt(numberOfTrials)));
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return (mean() + ((1.96 * stddev()) / Math.sqrt(numberOfTrials)));
}
// test client
public static void main(String[] args) {
PercolationStats percolationStats;
try {
int n = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
percolationStats = new PercolationStats(n, T);
StdOut.println("mean = " + percolationStats.mean());
StdOut.println("stddev = " + percolationStats.stddev());
StdOut.println("95% confidence interval = " + "[" + percolationStats.confidenceLo() + "," + percolationStats.confidenceHi() + "]");
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
StdOut.println("You must enter two arguments");
}
}
}