[Algorithms(Princeton)] Week1 - PercolationStats
1 public class PercolationStats { 2 3 private int N; 4 private int T; 5 private double[] results; 6 7 public PercolationStats(int N, int T) { 8 if (N <= 0 || T <= 0) { 9 throw new java.lang.IllegalArgumentException( 10 "N or T must be greater than 0"); 11 } 12 13 this.N = N; 14 this.T = T; 15 results = new double[T]; 16 17 for (int t = 0; t < T; t++) { 18 results[t] = run(); 19 } 20 } 21 22 private double run() { 23 Percolation percolation = new Percolation(N); 24 double count = 0; 25 26 while (!percolation.percolates()) { 27 count++; 28 29 // pick a random site 30 // (N+1 because second value to uniform is exclusive) 31 int i = StdRandom.uniform(1, N + 1); 32 int j = StdRandom.uniform(1, N + 1); 33 34 // generate new random sites until a blocked one is found 35 while (percolation.isOpen(i, j)) { 36 37 i = StdRandom.uniform(1, N + 1); 38 j = StdRandom.uniform(1, N + 1); 39 40 } 41 42 // open that site 43 percolation.open(i, j); 44 45 } 46 return count / (N * N); // percolation threshold estimate 47 } 48 49 public double mean() { 50 return StdStats.mean(results); 51 } 52 53 public double stddev() { 54 return StdStats.stddev(results); 55 } 56 57 public double confidenceHi() { 58 return mean() - 1.96 * stddev() / Math.sqrt(T); 59 } 60 61 public double confidenceLo() { 62 return mean() + 1.96 * stddev() / Math.sqrt(T); 63 } 64 65 public static void main(String[] args) { 66 67 int N; 68 int T; 69 70 if (args.length == 0) { 71 N = 100; 72 T = 10; 73 } else { 74 N = Integer.parseInt(args[0]); 75 T = Integer.parseInt(args[1]); 76 } 77 78 // double startTime = System.nanoTime(); 79 PercolationStats stats = new PercolationStats(N, T); 80 81 double confidenceLow = stats.confidenceHi(); 82 double confidenceHigh = stats.confidenceLo(); 83 84 System.out.println("mean = " + stats.mean()); 85 System.out.println("stddev = " + stats.stddev()); 86 System.out.println("95% confidence interval = " + confidenceLow + ", " 87 + confidenceHigh); 88 89 // performance measuring 90 // double endTime = System.nanoTime(); 91 // System.out.println("time cost: " + (endTime - startTime)); 92 93 } 94 }