coursera上Algotithms I的Assignment,用到了princeton大学提供的java库。
目的:判断是否连通percolates,然后用蒙特卡洛模拟随机打开site直到连通,重复这个过程,然后计算得到值(约59.2%)
原理:将顶部与底部设置一个虚拟的墙(顶部为0,底部为N*N+1)Union第一排与0和最后一排与N*N+1,若虚拟的墙与0联通则说明顶部与底部连通(perlocates)
题目见下:
Programming Assignment 1: Percolation
Write a program to estimate the value of the percolation threshold via Monte Carlo simulation.
Install a Java programming environment. Install a Java programming environment on your computer by following these step-by-step instructions for your operating system [ Mac OS X ·Windows · Linux ]. After following these instructions, the commands javac-algs4 and java-algs4 will classpath in algs4.jar, which contains Java classes for I/O and all of the algorithms in the textbook.
Note that, as of August 2015, you must use the named package version of algs.jar. To access a class, you need an import statement, such as the ones below:
import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF;
Percolation. Given a composite systems comprised of randomly distributed insulating and metallic materials: what fraction of the materials need to be metallic so that the composite system is an electrical conductor? Given a porous landscape with water on the surface (or oil below), under what conditions will the water be able to drain through to the bottom (or the oil to gush through to the surface)? Scientists have defined an abstract process known as percolation to model such situations.
The model. We model a percolation system using an N-by-N grid of sites. Each site is either open or blocked. A full site is an open site that can be connected to an open site in the top row via a chain of neighboring (left, right, up, down) open sites. We say the system percolates if there is a full site in the bottom row. In other words, a system percolates if we fill all open sites connected to the top row and that process fills some open site on the bottom row. (For the insulating/metallic materials example, the open sites correspond to metallic materials, so that a system that percolates has a metallic path from top to bottom, with full sites conducting. For the porous substance example, the open sites correspond to empty space through which water might flow, so that a system that percolates lets water fill open sites, flowing from top to bottom.)

The problem. In a famous scientific problem, researchers are interested in the following question: if sites are independently set to be open with probability p (and therefore blocked with probability 1 − p), what is the probability that the system percolates? When p equals 0, the system does not percolate; when p equals 1, the system percolates. The plots below show the site vacancy probability p versus the percolation probability for 20-by-20 random grid (left) and 100-by-100 random grid (right).


When N is sufficiently large, there is a threshold value p* such that when p < p* a random N-by-N grid almost never percolates, and when p > p*, a random N-by-N grid almost always percolates. No mathematical solution for determining the percolation threshold p* has yet been derived. Your task is to write a computer program to estimate p*.
Percolation data type. To model a percolation system, create a data type Percolation with the following API:
public class Percolation { public Percolation(int N) // create N-by-N grid, with all sites blocked public void open(int i, int j) // open site (row i, column j) if it is not open already public boolean isOpen(int i, int j) // is site (row i, column j) open? public boolean isFull(int i, int j) // is site (row i, column j) full? public boolean percolates() // does the system percolate? public static void main(String[] args) // test client (optional) }
Corner cases. By convention, the row and column indices i and j are integers between 1 and N, where (1, 1) is the upper-left site: Throw a java.lang.IndexOutOfBoundsException if any argument to open(), isOpen(), or isFull() is outside its prescribed range. The constructor should throw a java.lang.IllegalArgumentException if N ≤ 0.
Performance requirements. The constructor should take time proportional to N2; all methods should take constant time plus a constant number of calls to the union-find methods union(),find(), connected(), and count().
Monte Carlo simulation. To estimate the percolation threshold, consider the following computational experiment:
- Initialize all sites to be blocked.
- Repeat the following until the system percolates:
- Choose a site (row i, column j) uniformly at random among all blocked sites.
- Open the site (row i, column j).
- The fraction of sites that are opened when the system percolates provides an estimate of the percolation threshold.
For example, if sites are opened in a 20-by-20 lattice according to the snapshots below, then our estimate of the percolation threshold is 204/400 = 0.51 because the system percolates when the 204th site is opened.
![]() | ![]() | ![]() | ![]() |
By repeating this computation experiment T times and averaging the results, we obtain a more accurate estimate of the percolation threshold. Let xt be the fraction of open sites in computational experiment t. The sample mean μ provides an estimate of the percolation threshold; the sample standard deviation σ measures the sharpness of the threshold.
Assuming T is sufficiently large (say, at least 30), the following provides a 95% confidence interval for the percolation threshold:![]()
To perform a series of computational experiments, create a data type PercolationStats with the following API.
The constructor should throw a java.lang.IllegalArgumentException if either N ≤ 0 or T ≤ 0.public class PercolationStats { public PercolationStats(int N, int T) // perform T independent experiments on an N-by-N grid public double mean() // sample mean of percolation threshold public double stddev() // sample standard deviation of percolation threshold public double confidenceLo() // low endpoint of 95% confidence interval public double confidenceHi() // high endpoint of 95% confidence interval public static void main(String[] args) // test client (described below) }
Also, include a main() method that takes two command-line arguments N and T, performs T independent computational experiments (discussed above) on an N-by-N grid, and prints the mean, standard deviation, and the 95% confidence interval for the percolation threshold. Use StdRandom to generate random numbers; use StdStats to compute the sample mean and standard deviation.
% java PercolationStats 200 100 mean = 0.5929934999999997 stddev = 0.00876990421552567 95% confidence interval = 0.5912745987737567, 0.5947124012262428 % java PercolationStats 200 100 mean = 0.592877 stddev = 0.009990523717073799 95% confidence interval = 0.5909188573514536, 0.5948351426485464 % java PercolationStats 2 10000 mean = 0.666925 stddev = 0.11776536521033558 95% confidence interval = 0.6646167988418774, 0.6692332011581226 % java PercolationStats 2 100000 mean = 0.6669475 stddev = 0.11775205263262094 95% confidence interval = 0.666217665216461, 0.6676773347835391
Analysis of running time and memory usage (optional and not graded). Implement the Percolation data type using the quick find algorithm in QuickFindUF.
- Use Stopwatch to measure the total running time of PercolationStats for various values of N and T. How does doubling N affect the total running time? How does doubling T affect the total running time? Give a formula (using tilde notation) of the total running time on your computer (in seconds) as a single function of both N and T.
- Using the 64-bit memory-cost model from lecture, give the total memory usage in bytes (using tilde notation) that a Percolation object uses to model an N-by-N percolation system. Count all memory that is used, including memory for the union-find data structure.
Now, implement the Percolation data type using the weighted quick union algorithm in WeightedQuickUnionUF. Answer the questions in the previous paragraph.
Deliverables. Submit only Percolation.java (using the weighted quick-union algorithm from WeightedQuickUnionUF) and PercolationStats.java. We will supply algs4.jar. Your submission may not call library functions except those in StdIn, StdOut, StdRandom, StdStats, WeightedQuickUnionUF, and java.lang.
For fun. Create your own percolation input file and share it in the discussion forums. For some inspiration, do an image search for "nonogram puzzles solved."
代码:
public class Percolation {
private int N;
private UF uf;
private boolean[][] blocks;//grids the value represents if openned
public Percolation(int N) {
if(N<=0)System.out.println("N should>0");//throw new IndexOutOfBoundsException();
uf = new WUnionFind(N*N+2); //use WeightedUnionFind
for(int i=1;i<=N;i++){//connect the upper wall to 0 to simplify the model
uf.union(i, 0);
}
for(int i=N*N;i>N*(N-1);i--){
uf.union(i, N*N+1);
}
this.N = N;
blocks = new boolean[N+1][N+1];//N*N blocks but 0 row and 0 colum is not used
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++){
this.blocks[i][j] = false;
}
}
this.uf = uf;
}
public boolean open(int i,int j){
if(isOpen(i,j))return false;
if(i<=0||j<=0)throw new IndexOutOfBoundsException();
blocks[i][j] = true;
int id = (i-1)*N + j; //map 2D to 1D
//System.out.println("id"+id);</span>
<span style="white-space:pre"> </span>if(j>1&&blocks[i][j-1])uf.union(id, id-1);//check left
if(j<N&&blocks[i][j+1])uf.union(id, id+1);//check right
if(i>1&&blocks[i-1][j])uf.union(id, id - N);//check up
if(i<N&&blocks[i+1][j])uf.union(id, id + N);//check down
return true;
}
public boolean isOpen(int i,int j){
return blocks[i][j];
}
public boolean percolates() {
if(uf.isConnected(N*N+1,0))//N*N+1 is the virtual down wall and 0 is the virtual upper wall
return true;
return false;
}
public boolean isFull(int row, int col) {//if the grid is connected to the virtual upper wall
int id = (row - 1) * N + col;
if(uf.isConnected(id, 0)){
return true;
}
return false;
}
}
分析平均值以及偏差:<span style="white-space:pre"> </span>import java.util.Random;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>import edu.princeton.cs.algs4.Stopwatch;
<span style="white-space:pre"> </span>/*
<span style="white-space:pre"> </span> * data analysis
<span style="white-space:pre"> </span> */
<span style="white-space:pre"> </span>public class PercolationStats {
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>private double[] data;
<span style="white-space:pre"> </span>private Percolation p;
<span style="white-space:pre"> </span>private Random r = new Random();
<span style="white-space:pre"> </span>private int T;
<span style="white-space:pre"> </span>public PercolationStats(int N, int T){
<span style="white-space:pre"> </span>// perform T independent experiments on an N-by-N grid
<span style="white-space:pre"> </span>this.T = T;
<span style="white-space:pre"> </span>data = new double[T];
<span style="white-space:pre"> </span>for(int i=0;i<T;i++){
<span style="white-space:pre"> </span>p = new Percolation(N);
<span style="white-space:pre"> </span>int count = 0;
<span style="white-space:pre"> </span>while(true){
<span style="white-space:pre"> </span>int m = r.nextInt(N)+1 > N ? N : r.nextInt(N)+1;
<span style="white-space:pre"> </span>int n = r.nextInt(N)+1 > N ? N : r.nextInt(N)+1;
<span style="white-space:pre"> </span>if(p.open(m, n)) count++;
<span style="white-space:pre"> </span>if(p.percolates()) break;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>data[i] = (double)count / (N*N);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public double mean(){
<span style="white-space:pre"> </span>// sample mean of percolation threshold
<span style="white-space:pre"> </span>double total = 0;
<span style="white-space:pre"> </span>for(int i=0;i<T;i++){
<span style="white-space:pre"> </span>total += data[i];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return total/T;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public double stddev() {
<span style="white-space:pre"> </span>// sample standard deviation of percolation threshold
<span style="white-space:pre"> </span>double u = mean();
<span style="white-space:pre"> </span>double oSquare = 0;
<span style="white-space:pre"> </span>for(int i=0;i<T;i++){
<span style="white-space:pre"> </span>oSquare += (data[i]-u)*(data[i]-u)/(T-1);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return Math.sqrt(oSquare);
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>Stopwatch sw = new Stopwatch();
<span style="white-space:pre"> </span>PercolationStats ps = new PercolationStats(300,100);
<span style="white-space:pre"> </span>/*
<span style="white-space:pre"> </span> * if not use path compression the performance is much lower (try to comment the path compression)
<span style="white-space:pre"> </span> * ex:
<span style="white-space:pre"> </span> * if commented:<span style="white-space:pre"> </span>time:3.323
<span style="white-space:pre"> </span>0.5933672222222222
<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>0.00740732531520167
<span style="white-space:pre"> </span> <span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>else : <span style="white-space:pre"> </span>time:0.827
<span style="white-space:pre"> </span>0.5925326666666669
<span style="white-space:pre"> </span>0.0076565089624747
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span> *
<span style="white-space:pre"> </span> */
<span style="white-space:pre"> </span>double time = sw.elapsedTime();
<span style="white-space:pre"> </span>System.out.println("time:" + time);
<span style="white-space:pre"> </span>System.out.println(ps.mean());
<span style="white-space:pre"> </span>System.out.println(ps.stddev());
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="font-family: Simsun;">
public class WUnionFind implements UF{
<span style="white-space:pre"> </span>private int[] parent;
<span style="white-space:pre"> </span>private int[] size;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public WUnionFind(int N){
<span style="white-space:pre"> </span>parent = new int[N];
<span style="white-space:pre"> </span>size = new int[N];
<span style="white-space:pre"> </span>for(int i=0;i<N;i++){
<span style="white-space:pre"> </span>this.parent[i] = i;
<span style="white-space:pre"> </span>this.size[i] = 1;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public boolean isConnected(int i, int j) {
<span style="white-space:pre"> </span>return find(i)==find(j);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public void union(int p, int q) {
<span style="white-space:pre"> </span>int rootP = find(p);
<span style="white-space:pre"> </span>int rootQ = find(q);
<span style="white-space:pre"> </span>if(size[rootP]<size[rootQ]){//&&rootP!=0){
<span style="white-space:pre"> </span>parent[rootP] = rootQ;
<span style="white-space:pre"> </span>size[rootQ] += size[rootP];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>else {
<span style="white-space:pre"> </span>parent[rootQ] = rootP;
<span style="white-space:pre"> </span>size[rootP] += size[rootQ];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>//System.out.println("union "+p+" "+q);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public int find(int p) {
<span style="white-space:pre"> </span>while(p!=parent[p]){
<span style="white-space:pre"> </span>parent[p] = parent[parent[p]];//compression
<span style="white-space:pre"> </span>p = parent[p];
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>return p;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>WUnionFind uf = new WUnionFind(10);
<span style="white-space:pre"> </span>uf.union(1, 2);
<span style="white-space:pre"> </span>uf.union(2, 3);
<span style="white-space:pre"> </span>uf.union(5, 4);
<span style="white-space:pre"> </span>uf.union(6, 4);
<span style="white-space:pre"> </span>uf.union(2, 4);
<span style="white-space:pre"> </span>System.out.println(uf.isConnected(1, 9));
<span style="white-space:pre"> </span>System.out.println(uf.isConnected(8, 4));
<span style="white-space:pre"> </span>System.out.println(uf.isConnected(8, 7));
<span style="white-space:pre"> </span>}
}</span><span style="font-family:Arial, Helvetica, sans-serif;"><span style="font-style: normal; white-space: normal;">
</span></span>