Skip to main content

This assignment is due before 11:00PM on Wednesday, September 13, 2017. There are two parts to this homework assignment:

You’ll need to submit your solutions to both parts of the homework before the deadline.

Collaboration policy.

Programming Assignment 1: Percolation

Write a program to estimate the value of the percolation threshold via Monte Carlo simulation.

The goals of this part of the assignment are:

Install Java and Eclipse

You should install Java and the Eclipse IDE on your computer for your operating system. You should also download algs4.jar, which contains Java classes for I/O and all of the algorithms in the textbook, and import the jar file in your Eclipse project.

To access a class in algs4.jar from a Java class that you write, you will need to include import statements, such as the ones below:

import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.WeightedQuickUnionUF;

Note that your code must be in the default package; if you use a package statement, the autograder will not be able to assess your work.

Percolation

Given a composite system 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 -by- 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.)

Percolates
Does not percolate

The problem

In a famous scientific problem, researchers are interested in the following question: if sites are independently set to be open with probability (and therefore blocked with probability ), what is the probability that the system percolates? When equals 0, the system does not percolate; when 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).

Percolation threshold for 20-by-20 grid
Percolation threshold for 100-by-100 grid

When is sufficiently large, there is a threshold value such that when a random -by- grid almost never percolates, and when , a random -by- grid almost always percolates. No mathematical solution for determining the percolation threshold has yet been derived. Your task is to write a computer program to estimate .

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 row, int col)       // open site (row, col) if it is not open already
   public boolean isOpen(int row, int col)  // is site (row, col) open?
   public boolean isFull(int row, int col)  // is site (row, col) full?
   public int numberOfOpenSites()           // number of open sites
   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 are integers between 1 and , where (1, 1) is the upper-left site: Throw a java.lang.IllegalArgumentException if any argument to open(), isOpen(), or isFull() is outside its prescribed range. The constructor should throw a java.lang.IllegalArgumentException if ≤ 0.

Performance requirements

The constructor should take time proportional to ; 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:

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.

Percolation 50 sites 
50 open sites
Percolation 100 sites 
100 open sites
Percolation 150 sites 
150 open sites
Percolation 204 sites 
204 open sites

By repeating this computation experiment times and averaging the results, we obtain a more accurate estimate of the percolation threshold. Let be the fraction of open sites in computational experiment . The sample mean provides an estimate of the percolation threshold; the sample standard deviation ; measures the sharpness of the threshold.

Assuming 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.

public class PercolationStats {
   public PercolationStats(int n, int trials)    // perform trials 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)
}

The constructor should throw a java.lang.IllegalArgumentException if either ≤ 0 or trials ≤ 0. Also, include a main() method that takes two command-line arguments and , performs independent computational experiments (discussed above) on an -by- grid, and prints the sample mean, sample 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 sample 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 and . How does doubling change the total running time? How does doubling change 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 and .

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 and PercolationStats.java. Your Percolation.java should use the weighted quick-union algorithm from the WeightedQuickUnionUF class in the algs4.jar. Your submission may not call library functions except those in StdIn, StdOut, StdRandom, StdStats, WeightedQuickUnionUF, and packages and methods under java.lang like java.lang.Math.sqrt().

Written Assignment 1: Union-Find and Analysis of Algorithms

The goals of this assignment are to test your understanding of the material covered in sections 1.4 and 1.5 of the textbook, and the lecture and recitation materials. You should read the textbook chapters before doing this part of the assignment.

Written homeworks must be typeset in LaTeX and submitted in PDF format.

Q1. Weighted quick-union by height

Develop a UF implementation that uses the same basic strategy as weighted quick-union but keeps track of the tree height and always links the shorter tree to the taller one. Prove a logarithmic upper bound on the height of the trees with N nodes with your algorithm.

Q2. Different uses of the id array in Union Find.

For the following diagram:

  1. Give the contents of the id[] for the Quick Union algorithm discussed in class.
  2. Give the contents of the id[] for the Quick Find algorithm.

Q3: Analysis of Algorithms

For each of the statements below, please say whether it is true or false, and give a 1 sentence explanation of your answer.

  1. Worst case analysis provides a running time bound that holds for every input of length N. 

  2. Worst case analysis is usually easier to establish than average case analysis. 

  3. We retain lower order terms in asymptotic analysis, since we are concerned with getting a very accurate estimate of running time. 

  4. Constant factors can depend on system architecture, choice of compiler or programming language. 

  5. To establish the bounds on the class of algorithms that solve a problem, we typically implement an algorithm to establish the lower bound, and rely on a proof to establish the upper bound. 

  6. Big Oh provides a good estimate of the average running time for an algorithm. 

  7. Asymptotic analysis is concerned with large values of N and can be inaccurate for small N. 

  8. If an algorithm has a running time of Θ(N log N ) then: (say True/False for each of the items below, and explain each). 
 a. It is O(N log N). b. It is Ω(N log N). 
 c. It is optimal. 

  9. If the lower bound on the class of algorithms that solve a problem is an algorithm Ω(), and an algorithm in that class is O() then: 
 a. The algorithm is Θ(). b. The algorithm is Ω(). 
 c. The algorithm is optimal. 

  10. If two algorithms have the same running time in terms of Big Oh, then they will have equivalent running times in Tilde 


Q4: Evaluating the Claims of A Startup Company

Facebook has hired you as a special advisor to Mark Zuckerberg. Congrats - taking CIS 121 really paid off. Mark considers acquiring a startup in stealth mode. The company claims to have invented a new algorithm that will use polynomial time to solve a problem previously thought to be solvable in exponential time. The company refuses to release its code because it is worried that it will be stolen. They will allow you to do black box testing by sending whatever inputs you want to their server. You get back the output, and you can time how long it takes to run. Mark asks you to test it on the double, so you sketch out this chart.

Input size Response time
64 2.9
128 24
256 188
512 1503
1024 12026
  1. What is your estimate of the order of growth of the company’s algorithm? How did you arrive at this estimate?