-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPercolationStats.java
74 lines (66 loc) · 2.64 KB
/
PercolationStats.java
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
/******************************************************************************
* Compilation: javac-algs4 PercolationStats.java
* Execution: java-algs4 PercolationStats 100(n) 100(trials)
* Dependencies: Percolation.java
*
******************************************************************************/
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Stopwatch;
public class PercolationStats {
private final double mean;
private final double stddev;
private final double confidenceLo;
private final double confidenceHi;
// 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 <= 0 or trials <= 0");
}
double[] results = new double[trials];
for (int k = 0; k < trials; k++) {
int times = 0;
Percolation percolation = new Percolation(n);
while (!percolation.percolates()) {
int i = 1 + StdRandom.uniform(n);
int j = 1 + StdRandom.uniform(n);
if (!percolation.isOpen(i, j)) {
percolation.open(i, j);
times++;
}
}
results[k] = (double) times / (n*n);
}
mean = StdStats.mean(results);
stddev = StdStats.stddev(results);
confidenceLo = mean - 1.96 * stddev / Math.sqrt(trials);
confidenceHi = mean + 1.96 * stddev / Math.sqrt(trials);
}
// sample mean of percolation threshold
public double mean() {
return mean;
}
// sample standard deviation of percolation threshold
public double stddev() {
return stddev;
}
// low endpoint of 95% confidence interval
public double confidenceLo() {
return confidenceLo;
}
// high endpoint of 95% confidence interval
public double confidenceHi() {
return confidenceHi;
}
// test client (described below)
public static void main(String[] args) {
Stopwatch timer = new Stopwatch();
PercolationStats ps = new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
StdOut.println("Total running time: " + timer.elapsedTime() + " seconds");
String confidence = "[" + ps.confidenceLo() + ", " + ps.confidenceHi() + "]";
StdOut.println("mean = " + ps.mean());
StdOut.println("stddev = " + ps.stddev());
StdOut.println("95% confidence interval = " + confidence);
}
}