summaryrefslogtreecommitdiffstats
path: root/Algorithms/Part-I
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2013-03-04 14:06:25 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2013-11-15 17:38:13 +0100
commit5499e190c5fca84aca9cda4504172aaf3e98a91f (patch)
tree6f93fb897de7e4d3a79bbefb12a37221330bf31b /Algorithms/Part-I
parent1347b61e24c7f96c051d41874a7325a42941e62e (diff)
downloadcoursera-5499e190c5fca84aca9cda4504172aaf3e98a91f.zip
coursera-5499e190c5fca84aca9cda4504172aaf3e98a91f.tar.gz
Algorithms-I : 1-Percolation: app PercolationStats.java
Diffstat (limited to 'Algorithms/Part-I')
-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());
+ }
+}