码迷,mamicode.com
首页 > 编程语言 > 详细

AlgorithmsI Programming Assignment 1: PercolationStats.java

时间:2015-09-27 16:10:28      阅读:439      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享

技术分享

技术分享

import edu.princeton.cs.algs4.StdOut;    
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;    
/*
 *How do I generate a site uniformly at random among all blocked sites for use in PercolationStats? 
 * Pick a site at random (by using StdRandom to generate two integers between 1 and N) 
 * and use this site if it is blocked; if not, repeat. 
 */
public class PercolationStats {
   private int T; //T independent experiments
   private double[] fraction;
       
   public PercolationStats(int N, int T) {  // perform T independent experiments on an N-by-N grid
       if (N <= 0 || T <= 0) {
           throw new IllegalArgumentException("N and T must be bigger than 0");
       }
       this.T = T;
       fraction = new double[T];
      
       for (int count = 0; count < T; count++) {
           Percolation pr =  new Percolation(N);
           int openedSites = 0;
           while (!pr.percolates()) {
               int i = StdRandom.uniform(1, N+1);
               int j = StdRandom.uniform(1, N+1);
               if (!pr.isOpen(i, j)) {
                   pr.open(i, j);
                   openedSites++;
               }
           }
           fraction[count] = (double) openedSites / (N * N);
       }
   }
  
   public double mean() {                     // sample mean of percolation threshold
       return StdStats.mean(fraction);
   }
   
   public double stddev() {                 // sample standard deviation of percolation threshold
       return StdStats.stddev(fraction);
   }
   
   public double confidenceLo() {           // low  endpoint of 95% confidence interval
       return mean() - 1.96 * stddev() / Math.sqrt(T); 
   }
   
   public double confidenceHi() {      // high endpoint of 95% confidence interval
       return mean() + 1.96 * stddev() / Math.sqrt(T); 
   } 
  
   public static void main(String[] args)    // test client (described below)
   {
       int N = Integer.parseInt(args[0]);
       int T = Integer.parseInt(args[1]);
       PercolationStats ps = new PercolationStats(N, T);
       StdOut.println("mean                    = " + ps.mean());
       StdOut.println("stddev                  = " + ps.stddev());
       StdOut.println("95% confidence interval = "+ps.confidenceLo()+", "+ ps.confidenceHi());
   }
}

 

AlgorithmsI Programming Assignment 1: PercolationStats.java

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4842243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!