| 9 | import edu.princeton.cs.algs4.StdStats; |
| 10 | |
| 11 | public class PercolationStats { |
| 12 | private static final double CONST_K = 1.96; |
| 13 | private double[] thresholds; |
| 14 | |
| 15 | public PercolationStats(int n, int trials) { |
| 16 | if (n <= 0 || trials <= 0) |
| 17 | throw new IllegalArgumentException("n and trials should be larger than 0"); |
| 18 | // perform independent trials on an n-by-n grid |
| 19 | int trialsTimes = trials; |
| 20 | thresholds = new double[trialsTimes]; |
| 21 | // start trials |
| 22 | while (trials-- != 0) { |
| 23 | Percolation p = new Percolation(n); |
| 24 | while (!p.percolates()) { |
| 25 | int row, col; |
| 26 | while (true) { |
| 27 | row = StdRandom.uniformInt(1, n + 1); |
| 28 | col = StdRandom.uniformInt(1, n + 1); |
| 29 | if (p.isOpen(row, col)) continue; |
| 30 | p.open(row, col); |
| 31 | break; |
| 32 | } |
| 33 | } |
| 34 | thresholds[trials] = 1.0 * p.numberOfOpenSites() / (n * n); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // sample mean of percolation threshold |
| 39 | public double mean() { |
| 40 | return StdStats.mean(thresholds); |
| 41 | } |
| 42 | |
| 43 | // sample standard deviation of percolation threshold |
| 44 | public double stddev() { |
| 45 | return thresholds.length == 1 ? Double.NaN : StdStats.stddev(thresholds); |
| 46 | } |
| 47 | |
| 48 | // low endpoint of 95% confidence interval |
| 49 | public double confidenceLo() { |
| 50 | return mean() - CONST_K * stddev() / Math.sqrt(1.0 * thresholds.length); |
| 51 | } |
| 52 | |
| 53 | // high endpoint of 95% confidence interval |
| 54 | public double confidenceHi() { |
| 55 | return mean() + CONST_K * stddev() / Math.sqrt(1.0 * thresholds.length); |
| 56 | } |
| 57 | |
| 58 | public static void main(String[] args) { |
| 59 | int n = Integer.parseInt(args[0]); |
| 60 | int trials = Integer.parseInt(args[1]); |
| 61 | |
| 62 | PercolationStats ps = new PercolationStats(n, trials); |
| 63 | StdOut.println("mean = " + ps.mean()); |
| 64 | StdOut.println("stddev = " + ps.stddev()); |
| 65 | StdOut.println( |
| 66 | "95% confidence interval = [" + ps.confidenceLo() + ", " + ps.confidenceHi() + "]"); |
| 67 | } |
| 68 | } |
nothing calls this directly
no outgoing calls
no test coverage detected