-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPercolationStats.java
More file actions
98 lines (75 loc) · 2.92 KB
/
Copy pathPercolationStats.java
File metadata and controls
98 lines (75 loc) · 2.92 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* *****************************************************************************
* Name: Rafael Neves Moraes
*
* Description: To estimate the percolation threshold.
*
* Written: 8/05/2019
*
* % javac-algs4 PercolationStats.java
* % java-algs4 PercolationStats 200 100
*
**************************************************************************** */
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.Stopwatch;
public class PercolationStats {
private static final double CONFIDENCE_INDEX = 1.96;
private final int t; // Trials
private final double[] x;
private double mean;
private double stddev;
// perform trials independent experiments on an n-by-n grid
public PercolationStats(int n, int trials) {
if (n <= 0 || trials <= 0)
throw new IllegalArgumentException("n and trials must be gran than 0!");
t = trials;
x = new double[trials];
mean = Double.NaN;
stddev = Double.NaN;
double nn = n * n;
for (int i = 0; i < trials; i++) {
Percolation p = new Percolation(n);
while (!p.percolates()) {
int rone = StdRandom.uniform(1, n + 1);
int rtwo = StdRandom.uniform(1, n + 1);
if (p.isOpen(rone, rtwo))
continue;
p.open(rone, rtwo);
}
double op = p.numberOfOpenSites();
x[i] = op / nn;
}
}
// sample mean of percolation threshold
public double mean() {
if (Double.isNaN(mean))
mean = StdStats.mean(x);
return mean;
}
// sample standard deviation of percolation threshold
public double stddev() {
if (Double.isNaN(stddev))
stddev = StdStats.stddev(x);
return stddev;
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return mean() - (PercolationStats.CONFIDENCE_INDEX * (stddev() / Math.sqrt(t)));
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return mean() + (PercolationStats.CONFIDENCE_INDEX * (stddev() / Math.sqrt(t)));
}
// test client (described below)
public static void main(String[] args) {
Stopwatch sw = new Stopwatch();
int n = Integer.parseInt(args[0]);
int trials = Integer.parseInt(args[1]);
PercolationStats ps = new PercolationStats(n, trials);
System.out.println(String.format("mean: %s", ps.mean()));
System.out.println(String.format("stddev: %s", ps.stddev()));
System.out.println(String.format("95%% confidence interval: [%s,%s]",
ps.confidenceLo(), ps.confidenceHi()));
System.out.println(String.format("Running time: %ss", sw.elapsedTime()));
}
}