diff --git a/Percolation.class b/Percolation.class new file mode 100644 index 0000000..cbea07f Binary files /dev/null and b/Percolation.class differ diff --git a/Percolation.java b/Percolation.java index 2a628dc..4f22999 100644 --- a/Percolation.java +++ b/Percolation.java @@ -1,14 +1,161 @@ +import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF; 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? + + // gridLength is the length of the square grid. + // There are gridLength^2 non-virtual sites in the grid + private int gridLength; + + // two sites can percolate to one another if they are both open and connected: + // isOpen monitors open/closed state of each site. + private boolean[] isOpen; + + // percolation represents connectivity between sites. connected, open sites percolate to one another. + private WeightedQuickUnionUF percolation; + + // quick union structure for tracking fullness without backwash. + // similar to percolation above, but without bottom virtual site + private WeightedQuickUnionUF fullness; + + // index of virtual site that is connected to entire top row, initializes to 0. + private int virtualTopIndex; + + // index of virtual site that is connected to entire bottom row, initializes to (n^2)+1 + private int virtualBottomIndex; + + // converts between two dimensional coordinate system and site array index. + // throws exceptions on invalid bounds. valid indices are 1 : n^2 + // a is the row; b is the column + private int siteIndex(int a, int b) + { + checkBounds(a, b); + int x = b; + int y = a; + return (y - 1) * gridLength + (x); + } + + /* + * By convention, the indices a and b are integers between 1 and n, where (1, 1) is the upper-left site: + * Throw a java.lang.IndexOutOfBoundsException if either a or b is outside this range. + */ + private void checkBounds(int a, int b) + { + if (a > gridLength || a < 1 ) + { + throw new IndexOutOfBoundsException("row index a out of bounds"); + } + if (b > gridLength || b < 1) + { + throw new IndexOutOfBoundsException("column index b out of bounds"); + } + } + + // create n-by-n grid, with all sites blocked + public Percolation(int n) + { + if (n < 1) { + throw new IllegalArgumentException(); + } + gridLength = n; + int arraySize = n * n + 2; + isOpen = new boolean[arraySize]; + + virtualTopIndex = 0; + virtualBottomIndex = (n * n) + 1; + + isOpen[virtualTopIndex] = true; /// open virtual top site + isOpen[virtualBottomIndex] = true; /// open virtual bottom site + + percolation = new WeightedQuickUnionUF(arraySize); + fullness = new WeightedQuickUnionUF(arraySize); + for (int b = 1; b <= n; b++) + { + /// connect all top row sites to virtual top site + int a = 1; + int topSiteIndex = siteIndex(a, b); + percolation.union(virtualTopIndex, topSiteIndex); + fullness.union(virtualTopIndex, topSiteIndex); + + /// connect all bottom row sites to virtual bottom site + a = n; + int bottomSiteIndex = siteIndex(a, b); + percolation.union(virtualBottomIndex, bottomSiteIndex); + + } + }; + + // open site (row a, column b) if it is not already + public void open(int a, int b) + { + int siteIndex = siteIndex(a,b); + if (!isOpen[siteIndex]) + { + /// to open a site, change boolean value, and union with any adjacent open sites + isOpen[siteIndex] = true; - public static void main(String[] args) // test client (optional) + // before connecting to a neighbor, first check that site is not on an edge, and is open + if (b > 1 && isOpen(a, b - 1)) + { + int indexToLeft = siteIndex(a, b - 1); + percolation.union(siteIndex, indexToLeft); + fullness.union(siteIndex, indexToLeft); + } + + if (b < gridLength && isOpen(a, b + 1)) + { + int indexToRight = siteIndex(a, b + 1); + percolation.union(siteIndex, indexToRight); + fullness.union(siteIndex,indexToRight); + } + + if (a > 1 && isOpen(a - 1, b)) // site is not top edge + { + int indexToTop = siteIndex(a - 1, b); + percolation.union(siteIndex, indexToTop); + fullness.union(siteIndex,indexToTop); + } + + if (a < gridLength && isOpen(a + 1, b)) /// site is not on bottom edge + { + int indexToBottom = siteIndex(a + 1, b); + percolation.union(siteIndex, indexToBottom); + fullness.union(siteIndex,indexToBottom); + } + } + }; + + // is site (row a, column b) open? + //// openness represented by boolean value in isOpen array + public boolean isOpen(int a, int b) + { + int siteIndex = siteIndex(a, b); + return isOpen[siteIndex]; + } + + // is site (row a, column b) full? + /// fullness represented by union with virtual top node + public boolean isFull(int a, int b) + { + int siteIndex = siteIndex(a, b); + //return (percolation.connected(virtualTopIndex,siteIndex) && isOpen[siteIndex]); + return (fullness.connected(virtualTopIndex,siteIndex) && isOpen[siteIndex]); + } + + // does the system percolate? + public boolean percolates() { + if (gridLength > 1) { + return percolation.connected(virtualTopIndex,virtualBottomIndex); + } + else { + return isOpen[siteIndex(1,1)]; + } + + } + + public static void main(String[] args) { + + } } \ No newline at end of file diff --git a/PercolationStats.class b/PercolationStats.class new file mode 100644 index 0000000..9219224 Binary files /dev/null and b/PercolationStats.class differ diff --git a/PercolationStats.java b/PercolationStats.java index f7d9c1b..0a31f95 100644 --- a/PercolationStats.java +++ b/PercolationStats.java @@ -1,13 +1,72 @@ +import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF; 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) + + // holds each experiment's percolation threshold result + private double[] thresholdResults; + + private int T; + // perform T independent computational experiments on an n-by-n grid + + public PercolationStats(int n, int T) + { + ///The constructor should throw a java.lang.IllegalArgumentException if either n <= 0 or T >= 0. + if (n < 1 || T < 1) + { + throw new IllegalArgumentException("both arguments n and T must be greater than 1"); + } + + this.T = T; + thresholdResults = new double[T]; + for (int t = 0; t < T; t++) + { + Percolation percolation = new Percolation(n); + int openSites = 0; + while (!percolation.percolates()) + { + int a = StdRandom.uniform(1, n+1); + int b = StdRandom.uniform(1, n+1); + + if (!percolation.isOpen(a, b)) + { + percolation.open(a, b); + openSites += 1; + } + } + double threshold = (double)openSites/(double)(n * n); + thresholdResults[t] = threshold; + } + } + + // sample mean of percolation threshold + public double mean() + { + return StdStats.mean(thresholdResults); + } + + // sample standard deviation of percolation threshold + public double stddev() + { + return StdStats.stddev(thresholdResults); + } + + // returns lower bound of the 95% confidence interval + public double confidenceLo() + { + return mean() - (1.96 * stddev() / Math.sqrt(T)); + } + + // returns upper bound of the 95% confidence interval + public double confidenceHi() + { + return mean() + (1.96 * stddev() / Math.sqrt(T)); + } + + public static void main(String[] args) { + + } + } \ No newline at end of file diff --git a/StdOut.java b/StdOut.java new file mode 100644 index 0000000..4501df7 --- /dev/null +++ b/StdOut.java @@ -0,0 +1,318 @@ +/****************************************************************************** + * Compilation: javac StdOut.java + * Execution: java StdOut + * Dependencies: none + * + * Writes data of various types to standard output. + * + ******************************************************************************/ + +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.Locale; + +/** + * This class provides methods for printing strings and numbers to standard output. + *

+ * Getting started. + * To use this class, you must have {@code StdOut.class} in your + * Java classpath. If you used our autoinstaller, you should be all set. + * Otherwise, download + * StdOut.java + * and put a copy in your working directory. + *

+ * Here is an example program that uses {@code StdOut}: + *

+ *   public class TestStdOut {
+ *       public static void main(String[] args) {
+ *           int a = 17;
+ *           int b = 23;
+ *           int sum = a + b;
+ *           StdOut.println("Hello, World");
+ *           StdOut.printf("%d + %d = %d\n", a, b, sum);
+ *       }
+ *   }
+ *  
+ *

+ * Differences with System.out. + * The behavior of {@code StdOut} is similar to that of {@link System#out}, + * but there are a few subtle differences: + *

+ *

+ * Reference. + * For additional documentation, + * see Section 1.5 of + * Computer Science: An Interdisciplinary Approach + * by Robert Sedgewick and Kevin Wayne. + * + * @author Robert Sedgewick + * @author Kevin Wayne + */ +public final class StdOut { + + // force Unicode UTF-8 encoding; otherwise it's system dependent + private static final String CHARSET_NAME = "UTF-8"; + + // assume language = English, country = US for consistency with StdIn + private static final Locale LOCALE = Locale.US; + + // send output here + private static PrintWriter out; + + // this is called before invoking any methods + static { + try { + out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true); + } + catch (UnsupportedEncodingException e) { + System.out.println(e); + } + } + + // don't instantiate + private StdOut() { } + + /** + * Closes standard output. + */ + public static void close() { + out.close(); + } + + /** + * Terminates the current line by printing the line-separator string. + */ + public static void println() { + out.println(); + } + + /** + * Prints an object to this output stream and then terminates the line. + * + * @param x the object to print + */ + public static void println(Object x) { + out.println(x); + } + + /** + * Prints a boolean to standard output and then terminates the line. + * + * @param x the boolean to print + */ + public static void println(boolean x) { + out.println(x); + } + + /** + * Prints a character to standard output and then terminates the line. + * + * @param x the character to print + */ + public static void println(char x) { + out.println(x); + } + + /** + * Prints a double to standard output and then terminates the line. + * + * @param x the double to print + */ + public static void println(double x) { + out.println(x); + } + + /** + * Prints an integer to standard output and then terminates the line. + * + * @param x the integer to print + */ + public static void println(float x) { + out.println(x); + } + + /** + * Prints an integer to standard output and then terminates the line. + * + * @param x the integer to print + */ + public static void println(int x) { + out.println(x); + } + + /** + * Prints a long to standard output and then terminates the line. + * + * @param x the long to print + */ + public static void println(long x) { + out.println(x); + } + + /** + * Prints a short integer to standard output and then terminates the line. + * + * @param x the short to print + */ + public static void println(short x) { + out.println(x); + } + + /** + * Prints a byte to standard output and then terminates the line. + *

+ * To write binary data, see {@link BinaryStdOut}. + * + * @param x the byte to print + */ + public static void println(byte x) { + out.println(x); + } + + /** + * Flushes standard output. + */ + public static void print() { + out.flush(); + } + + /** + * Prints an object to standard output and flushes standard output. + * + * @param x the object to print + */ + public static void print(Object x) { + out.print(x); + out.flush(); + } + + /** + * Prints a boolean to standard output and flushes standard output. + * + * @param x the boolean to print + */ + public static void print(boolean x) { + out.print(x); + out.flush(); + } + + /** + * Prints a character to standard output and flushes standard output. + * + * @param x the character to print + */ + public static void print(char x) { + out.print(x); + out.flush(); + } + + /** + * Prints a double to standard output and flushes standard output. + * + * @param x the double to print + */ + public static void print(double x) { + out.print(x); + out.flush(); + } + + /** + * Prints a float to standard output and flushes standard output. + * + * @param x the float to print + */ + public static void print(float x) { + out.print(x); + out.flush(); + } + + /** + * Prints an integer to standard output and flushes standard output. + * + * @param x the integer to print + */ + public static void print(int x) { + out.print(x); + out.flush(); + } + + /** + * Prints a long integer to standard output and flushes standard output. + * + * @param x the long integer to print + */ + public static void print(long x) { + out.print(x); + out.flush(); + } + + /** + * Prints a short integer to standard output and flushes standard output. + * + * @param x the short integer to print + */ + public static void print(short x) { + out.print(x); + out.flush(); + } + + /** + * Prints a byte to standard output and flushes standard output. + * + * @param x the byte to print + */ + public static void print(byte x) { + out.print(x); + out.flush(); + } + + /** + * Prints a formatted string to standard output, using the specified format + * string and arguments, and then flushes standard output. + * + * + * @param format the format string + * @param args the arguments accompanying the format string + */ + public static void printf(String format, Object... args) { + out.printf(LOCALE, format, args); + out.flush(); + } + + /** + * Prints a formatted string to standard output, using the locale and + * the specified format string and arguments; then flushes standard output. + * + * @param locale the locale + * @param format the format string + * @param args the arguments accompanying the format string + */ + public static void printf(Locale locale, String format, Object... args) { + out.printf(locale, format, args); + out.flush(); + } + + /** + * Unit tests some of the methods in {@code StdOut}. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + + // write to stdout + StdOut.println("Test"); + StdOut.println(17); + StdOut.println(true); + StdOut.printf("%.6f\n", 1.0/7.0); + } + +}