-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
71 lines (54 loc) · 2.06 KB
/
PercolationStats.java
File metadata and controls
71 lines (54 loc) · 2.06 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
/* *****************************************************************************
* Name: Spandan Mishra
* Date: 11th Mar'19
* Description: Calculate percolation threshold
**************************************************************************** */
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
public class PercolationStats {
private static final double CONFIDENCE_95 = 1.96;
private final int t;
// private int n;
private final double[] percThresholds;
public PercolationStats(int n, int t) {
if (n <= 0 || t <= 0)
throw new IllegalArgumentException("Invalid n or t");
this.t = t;
// this.n = n;
percThresholds = new double[t];
for (int i = 0; i < t; ++i) {
Percolation p = new Percolation(n);
int openSites = 0; // open sites when system percolates
while (!p.percolates()) {
int row = StdRandom.uniform(1, n + 1);
int col = StdRandom.uniform(1, n + 1);
if (!p.isOpen(row, col)) {
p.open(row, col);
openSites++;
}
}
double gridSize = n * n;
percThresholds[i] = openSites / gridSize;
}
}
public double mean() {
return StdStats.mean(percThresholds);
}
public double stddev() {
return StdStats.stddev(percThresholds);
}
public double confidenceLo() {
return mean() - ((CONFIDENCE_95 * Math.sqrt(stddev())) / Math.sqrt(t));
}
public double confidenceHi() {
return mean() + ((CONFIDENCE_95 * Math.sqrt(stddev())) / Math.sqrt(t));
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int t = Integer.parseInt(args[1]);
PercolationStats pst = new PercolationStats(n, t);
System.out.println("mean = " + pst.mean());
System.out.println("stdev = " + pst.stddev());
System.out.println("hi = " + pst.confidenceHi() + " lo = " + pst.confidenceLo());
}
}