Advertisement
jules0707

PercolationStats

Sep 7th, 2020 (edited)
1,055
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. import edu.princeton.cs.algs4.StdRandom;
  2. import edu.princeton.cs.algs4.StdStats;
  3.  
  4. public class PercolationStats {
  5.     private static final double CONFIDENCE_95 = 1.96;
  6.     private final int times;
  7.     private final double stddev;
  8.     private final double mean;
  9.  
  10.     public PercolationStats(int n, int times) {
  11.         this.times = times;
  12.         if (n <= 0 || times <= 0)
  13.             throw new IllegalArgumentException("not valid indices");
  14.  
  15.         double [] thresholds = new double[times];
  16.         // runs times times the monteCarlo simulation
  17.         for (int i = 0; i < times; i++) {
  18.             thresholds[i] = monteCarlo(n);
  19.         }
  20.         mean = StdStats.mean(thresholds);
  21.         stddev = StdStats.stddev(thresholds);
  22.     }
  23.  
  24.     public double mean() {
  25.         return mean;
  26.     }
  27.  
  28.     public double stddev() {
  29.         return stddev;
  30.     }
  31.  
  32.     public double confidenceLo() {
  33.         return (mean - ((CONFIDENCE_95 * stddev) / Math.sqrt(times)));
  34.     }
  35.  
  36.     public double confidenceHi() {
  37.         return (mean + ((CONFIDENCE_95 * stddev) / Math.sqrt(times)));
  38.     }
  39.  
  40.     private double monteCarlo(int n) {
  41.         Percolation percolation = new Percolation(n);
  42.         int p;
  43.         int q;
  44.         int opened = 0;
  45.         // as long as the system does not percolate whe open a new random site
  46.         while (!percolation.percolates()) {
  47.             p = StdRandom.uniform(1, n + 1); // a random site index in a n size grid + 1 as last item is excluded
  48.             q = StdRandom.uniform(1, n + 1); // an other random site
  49.             if (!percolation.isOpen(p, q)) {
  50.                 percolation.open(p, q);
  51.                 opened++;
  52.             }
  53.         }
  54.         return opened * 1.0 / (n * n);
  55.     }
  56.  
  57.     public static void main(String[] args) {
  58.         int n = Integer.parseInt(args[0]);
  59.         int t = Integer.parseInt(args[1]);
  60.         PercolationStats stats = new PercolationStats(n, t);
  61.         System.out.println("mean                   = " + stats.mean);
  62.         System.out.println("stddev                  = " + stats.stddev);
  63.         System.out.println("95% confidence interval = [" + stats.confidenceLo()
  64.                 + ", " + stats.confidenceHi() + " ]");
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement