summaryrefslogtreecommitdiffstats
path: root/Algorithms/Part-I/1-Percolation
diff options
context:
space:
mode:
Diffstat (limited to 'Algorithms/Part-I/1-Percolation')
-rw-r--r--Algorithms/Part-I/1-Percolation/PercolationStats.java72
1 files changed, 72 insertions, 0 deletions
diff --git a/Algorithms/Part-I/1-Percolation/PercolationStats.java b/Algorithms/Part-I/1-Percolation/PercolationStats.java
new file mode 100644
index 0000000..9f7a0e9
--- /dev/null
+++ b/Algorithms/Part-I/1-Percolation/PercolationStats.java
@@ -0,0 +1,72 @@
+/* vim: set expandtab tabstop=4 shiftwidth=4 : */
+
+public class PercolationStats
+{
+ private double[] results;
+ private double mean;
+ private double stddev;
+ private int N;
+
+ // perform T independent computational experiments on an N-by-N grid
+ public PercolationStats(int N, int T)
+ {
+ if (N < 1 || T < 1)
+ throw new java.lang.IllegalArgumentException("received value < 1");
+ this.N = N;
+ results = new double[T];
+ int n = N*N;
+ for (int t = 0; t < T; t++)
+ {
+ double c = 0;
+ Percolation p = new Percolation(N);
+ do
+ {
+ int i = StdRandom.uniform(1, N+1);
+ int j = StdRandom.uniform(1, N+1);
+ if (!p.isOpen(i, j)) {
+ p.open(i, j);
+ c += 1;
+ }
+ }
+ while(!p.percolates());
+ results[t] = c / n;
+ }
+ mean = StdStats.mean(results);
+ stddev = StdStats.stddev(results);
+ }
+
+ // sample mean of percolation threshold
+ public double mean()
+ {
+ return mean;
+ }
+
+ // sample standard deviation of percolation threshold
+ public double stddev()
+ {
+ return stddev;
+ }
+
+ // returns lower bound of the 95% confidence interval
+ public double confidenceLo()
+ {
+ return mean - 1.96*stddev/Math.sqrt(N);
+ }
+
+ // returns upper bound of the 95% confidence interval
+ public double confidenceHi()
+ {
+ return mean + 1.96*stddev/Math.sqrt(N);
+ }
+
+ // test client
+ public static void main(String[] args) {
+ int N = Integer.parseInt(args[0]);
+ int T = Integer.parseInt(args[1]);
+ PercolationStats stats = new PercolationStats(N, T);
+ System.out.printf("mean = %.16f\n", stats.mean());
+ System.out.printf("stddev = %.16f\n", stats.stddev());
+ System.out.printf("95%% confidence interval = %.16f, %.16f\n\n",
+ stats.confidenceLo(), stats.confidenceHi());
+ }
+}