Write a program to estimate the value of the percolation threshold via Monte Carlo simulation.
import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation { // creates n-by-n grid, with all sites initially blocked public Percolation(int n) // opens the site (row, col) if it is not open already public void open(int row, int col) // is the site (row, col) open? public boolean isOpen(int row, int col) // is the site (row, col) full? public boolean isFull(int row, int col) // returns the number of open sites public int numberOfOpenSites() // does the system percolate? public boolean percolates() // test client (optional) public static void main(String[] args) }
--> \[ \overline x = \frac{x_1 \, + \, x_2 \, + \, \cdots \, + \, x_{T}}{T}, \quad s^2 = \frac{(x_1 - \overline x )^2 \, + \, (x_2 - \overline x )^2 \,+\, \cdots \,+\, (x_{T} - \overline x )^2}{T-1} \]
--> \[ \left [ \; \overline x - \frac {1.96 s}{\sqrt{T}}, \;\; \overline x + \frac {1.96 s}{\sqrt{T}} \; \right] \]
public class PercolationStats { // perform independent trials on an n-by-n grid public PercolationStats(int n, int trials) // sample mean of percolation threshold public double mean() // sample standard deviation of percolation threshold public double stddev() // low endpoint of 95% confidence interval public double confidenceLo() // high endpoint of 95% confidence interval public double confidenceHi() // test client (see below) public static void main(String[] args) }
~/Desktop/percolation> java-algs4 PercolationStats 200 100 mean = 0.5929934999999997 stddev = 0.00876990421552567 95% confidence interval = [0.5912745987737567, 0.5947124012262428] ~/Desktop/percolation> java-algs4 PercolationStats 200 100 mean = 0.592877 stddev = 0.009990523717073799 95% confidence interval = [0.5909188573514536, 0.5948351426485464] ~/Desktop/percolation> java-algs4 PercolationStats 2 10000 mean = 0.666925 stddev = 0.11776536521033558 95% confidence interval = [0.6646167988418774, 0.6692332011581226] ~/Desktop/percolation> java-algs4 PercolationStats 2 100000 mean = 0.6669475 stddev = 0.11775205263262094 95% confidence interval = [0.666217665216461, 0.6676773347835391]
Instantly share code, notes, and snippets.
Chayemor / Percolation.java
- Download ZIP
- Star ( 2 ) 2 You must be signed in to star a gist
- Fork ( 0 ) 0 You must be signed in to fork a gist
- Embed Embed this gist in your website.
- Share Copy sharable link for this gist.
- Clone via HTTPS Clone using the web URL.
- Learn more about clone URLs
- Save Chayemor/296fa13fa86bb35250c9e66e991f02c5 to your computer and use it in GitHub Desktop.
/* ***************************************************************************** | |
* Name: Johanna Mesa Ramos | |
* Coursera User ID: c02b4bb527298de170192d644483baeb | |
* Last modified: 06/07/2020 | |
* Course: Algorithms, Part I https://www.coursera.org/learn/algorithms-part1 | |
**************************************************************************** */ | |
import edu.princeton.cs.algs4.WeightedQuickUnionUF; | |
public class Percolation { | |
private WeightedQuickUnionUF gridBackwash; | |
private WeightedQuickUnionUF grid; | |
private boolean[] nodeStates; | |
private int n; | |
private int top; | |
private int bottom; | |
private int openSites; | |
/** | |
* Creates n-by-n nodeStates, with all sites initially blocked | |
* Creates n-by-n + 2 WeightedQuickUnionUF gridBackwash, the +2 is for virtual top/bottom nodes | |
* Creates n-by-n + 1 WeightedQuickUnionUF grid, the +1 is for only the top virtual node and to | |
* avoid backwash | |
* in the method isFull | |
* | |
* @param n Dimension of the grid | |
*/ | |
public Percolation(int n) { | |
if (n < 1) | |
throw new java.lang.IllegalArgumentException( | |
"Stop right there, N must be greater than 0"); | |
this.n = n; | |
top = get1DIndex(n, n) + 1; | |
bottom = get1DIndex(n, n) + 2; | |
openSites = 0; | |
gridBackwash = new WeightedQuickUnionUF(n * n + 2); | |
grid = new WeightedQuickUnionUF(n * n + 1); // Only add top virtual node | |
nodeStates = new boolean[n * n]; | |
} | |
/** | |
* @param r row index, -1 because problem is 1 index based | |
* @param c col index, -1 because problem is 1 index based | |
* @return index from 2D array mapped to 1D array | |
*/ | |
private int get1DIndex(int r, int c) { | |
r -= 1; | |
c -= 1; | |
return (r * n) + c; | |
} | |
private boolean outOfRange(int row, int col, boolean throwEx) { | |
if (row < 1 || col < 1 || row > n || col > n) { | |
if (throwEx) | |
throw new java.lang.IllegalArgumentException("Values are out of range"); | |
return false; | |
} | |
return true; | |
} | |
public void open(int row, int col) { | |
outOfRange(row, col, true); | |
if (isOpen(row, col)) | |
return; | |
int i = get1DIndex(row, col); | |
nodeStates[i] = true; | |
openSites += 1; | |
if (row == 1) { | |
gridBackwash.union(top, i); | |
grid.union(top, i); | |
} | |
if (row == n) | |
gridBackwash.union(bottom, i); | |
union(row - 1, col, i); | |
union(row, col + 1, i); | |
union(row + 1, col, i); | |
union(row, col - 1, i); | |
} | |
private void union(int r, int c, int to) { | |
if (!outOfRange(r, c, false) || !isOpen(r, c)) | |
return; | |
gridBackwash.union(get1DIndex(r, c), to); | |
grid.union(get1DIndex(r, c), to); | |
} | |
public boolean isOpen(int row, int col) { | |
outOfRange(row, col, true); | |
return nodeStates[get1DIndex(row, col)]; | |
} | |
/** | |
* 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. | |
* | |
* @param row | |
* @param col | |
* @return boolean | |
*/ | |
public boolean isFull(int row, int col) { | |
outOfRange(row, col, true); | |
return isOpen(row, col) && grid.connected(get1DIndex(row, col), top); | |
} | |
public int numberOfOpenSites() { | |
return openSites; | |
} | |
public boolean percolates() { | |
return gridBackwash.connected(bottom, top); | |
} | |
public static void main(String[] args) { | |
} | |
} |
/* ***************************************************************************** | |
* Name: Johanna Mesa Ramos | |
* Coursera User ID: c02b4bb527298de170192d644483baeb | |
* Last modified: 06/07/2020 | |
* Course: Algorithms, Part I https://www.coursera.org/learn/algorithms-part1 | |
**************************************************************************** */ | |
import edu.princeton.cs.algs4.StdRandom; | |
import edu.princeton.cs.algs4.StdStats; | |
public class PercolationStats { | |
private Percolation perc; | |
private int size; | |
private int trials; | |
private double[] stats; | |
// perform independent trials on an n-by-n grid | |
public PercolationStats(int n, int trials) { | |
if (n < 1 || trials < 1) | |
throw new java.lang.IllegalArgumentException( | |
"Halt, n and trials must be greater than 0"); | |
this.trials = trials; | |
size = n; | |
stats = new double[trials]; | |
generateStats(); | |
} | |
private void generateStats() { | |
Percolation per; | |
for (int i = 0; i < trials; ++i) { | |
per = new Percolation(size); | |
while (!per.percolates()) { | |
per.open(StdRandom.uniform(1, size + 1), StdRandom.uniform(1, size + 1)); | |
} | |
stats[i] = (double) per.numberOfOpenSites() / (size * size); | |
} | |
} | |
public double mean() { | |
return StdStats.mean(stats); | |
} | |
public double stddev() { | |
return StdStats.stddev(stats); | |
} | |
// low endpoint of 95% confidence interval | |
public double confidenceLo() { | |
return mean() - (1.96 * stddev()) / Math.sqrt(size); | |
} | |
// high endpoint of 95% confidence interval | |
public double confidenceHi() { | |
return mean() + (1.96 * stddev()) / Math.sqrt(size); | |
} | |
public static void main(String[] args) { | |
PercolationStats ps = new PercolationStats(Integer.parseInt(args[0]), | |
Integer.parseInt(args[1])); | |
System.out.format("mean = %.16f %n", ps.mean()); | |
System.out.format("sttdev = %.16f %n", ps.stddev()); | |
System.out.format("95%% confidence interval = [%.16f, %.16f] %n", ps.confidenceLo(), | |
ps.confidenceHi()); | |
} | |
} |
See the Assessment Guide for information on how to interpret this report. | |
Want to receive personalized feedback on this submission? | |
You can pay to have a teaching assistant read and provide | |
personalized feedback on your submission at https://mooc.codepost.io. | |
ASSESSMENT SUMMARY | |
Compilation: FAILED (0 errors, 2 warnings) | |
API: PASSED | |
Spotbugs: PASSED | |
PMD: FAILED (12 warnings) | |
Checkstyle: FAILED (0 errors, 4 warnings) | |
Correctness: 36/38 tests passed | |
Memory: 8/8 tests passed | |
Timing: 20/20 tests passed | |
Aggregate score: 91.84% | |
[Compilation: 5%, API: 5%, Spotbugs: 0%, PMD: 0%, Checkstyle: 0%, Correctness: 60%, Memory: 10%, Timing: 20%] | |
ASSESSMENT DETAILS | |
The following files were submitted: | |
---------------------------------- | |
3.5K Jul 2 17:07 Percolation.java | |
2.2K Jul 2 17:07 PercolationStats.java | |
******************************************************************************** | |
* COMPILING | |
******************************************************************************** | |
% javac Percolation.java | |
*----------------------------------------------------------- | |
Percolation.java:109: warning: [deprecation] connected(int,int) in WeightedQuickUnionUF has been deprecated | |
return isOpen(row, col) && grid.connected(get1DIndex(row, col), top); | |
^ | |
Percolation.java:117: warning: [deprecation] connected(int,int) in WeightedQuickUnionUF has been deprecated | |
return gridBackwash.connected(bottom, top); | |
^ | |
2 warnings | |
% javac PercolationStats.java | |
*----------------------------------------------------------- | |
================================================================ | |
Checking the APIs of your programs. | |
*----------------------------------------------------------- | |
Percolation: | |
PercolationStats: | |
================================================================ | |
******************************************************************************** | |
* CHECKING STYLE AND COMMON BUG PATTERNS | |
******************************************************************************** | |
% spotbugs *.class | |
*----------------------------------------------------------- | |
================================================================ | |
% pmd . | |
*----------------------------------------------------------- | |
Percolation.java:11: The private instance (or static) variable 'gridBackwash' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
Percolation.java:12: The private instance (or static) variable 'grid' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
Percolation.java:14: The private instance (or static) variable 'n' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
Percolation.java:15: The private instance (or static) variable 'top' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
Percolation.java:16: The private instance (or static) variable 'bottom' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
Percolation.java:30: Unnecessary use of fully qualified name 'java.lang.IllegalArgumentException' due to existing implicit import 'java.lang.*'. [UnnecessaryFullyQualifiedName] | |
Percolation.java:56: Unnecessary use of fully qualified name 'java.lang.IllegalArgumentException' due to existing implicit import 'java.lang.*'. [UnnecessaryFullyQualifiedName] | |
Percolation.java:120: The method body is empty. If this is your intent, document it with a comment. [UncommentedEmptyMethodBody] | |
PercolationStats.java:12: Avoid unused private instance (or static) variables, such as 'perc'. [UnusedPrivateField] | |
PercolationStats.java:13: The private instance (or static) variable 'size' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
PercolationStats.java:14: The private instance (or static) variable 'trials' can be made 'final'; it is initialized only in the declaration or constructor. [ImmutableField] | |
PercolationStats.java:20: Unnecessary use of fully qualified name 'java.lang.IllegalArgumentException' due to existing implicit import 'java.lang.*'. [UnnecessaryFullyQualifiedName] | |
PMD ends with 12 warnings. | |
================================================================ | |
% checkstyle *.java | |
*----------------------------------------------------------- | |
[WARN] Percolation.java:30: Java automatically imports all classes and interfaces in the package 'java.lang'. So, there is no need to import such classes or interfaces; you can refer directly to them without the 'java.lang' prefix. [UnnecessaryJavaLang] | |
[WARN] Percolation.java:56: Java automatically imports all classes and interfaces in the package 'java.lang'. So, there is no need to import such classes or interfaces; you can refer directly to them without the 'java.lang' prefix. [UnnecessaryJavaLang] | |
[WARN] PercolationStats.java:20: Java automatically imports all classes and interfaces in the package 'java.lang'. So, there is no need to import such classes or interfaces; you can refer directly to them without the 'java.lang' prefix. [UnnecessaryJavaLang] | |
Checkstyle ends with 0 errors and 3 warnings. | |
% custom checkstyle checks for Percolation.java | |
*----------------------------------------------------------- | |
% custom checkstyle checks for PercolationStats.java | |
*----------------------------------------------------------- | |
[WARN] PercolationStats.java:7:1: The constant '1.96' appears more than once. Define a constant variable (such as 'CONFIDENCE_95') to hold the constant '1.96'. [NumericLiteralCount] | |
Checkstyle ends with 0 errors and 1 warning. | |
================================================================ | |
******************************************************************************** | |
* TESTING CORRECTNESS | |
******************************************************************************** | |
Testing correctness of Percolation | |
*----------------------------------------------------------- | |
Running 21 total tests. | |
Tests 1 through 7 create a Percolation object using your code, then repeatedly | |
open sites by calling open(). After each call to open(), it checks the return | |
values of isOpen(), percolates(), numberOfOpenSites(), and isFull() in that order. | |
Tests 12 through 15 create a Percolation object using your code, then repeatedly | |
call the methods open(), isOpen(), isFull(), percolates(), and, numberOfOpenSites() | |
in random order with probabilities p = (p1, p2, p3, p4, p5). The tests stop | |
immediately after the system percolates. | |
Tests 18 through 21 test backwash. | |
Except as noted, a site is opened at most once. | |
Test 1: open predetermined list of sites using file inputs | |
* filename = input6.txt | |
* filename = input8.txt | |
* filename = input8-no.txt | |
* filename = input10-no.txt | |
* filename = greeting57.txt | |
* filename = heart25.txt | |
==> passed | |
Test 2: open random sites until the system percolates | |
* n = 3 | |
* n = 5 | |
* n = 10 | |
* n = 10 | |
* n = 20 | |
* n = 20 | |
* n = 50 | |
* n = 50 | |
==> passed | |
Test 3: open predetermined sites for n = 1 and n = 2 (corner case test) | |
* filename = input1.txt | |
* filename = input1-no.txt | |
* filename = input2.txt | |
* filename = input2-no.txt | |
==> passed | |
Test 4: check predetermined sites with long percolating path | |
* filename = snake13.txt | |
* filename = snake101.txt | |
==> passed | |
Test 5: open every site | |
* filename = input5.txt | |
==> passed | |
Test 6: open random sites until the system percolates, | |
allowing open() to be called on a site more than once | |
* n = 3 | |
* n = 5 | |
* n = 10 | |
* n = 10 | |
* n = 20 | |
* n = 20 | |
* n = 50 | |
* n = 50 | |
==> passed | |
Test 7: open random sites with large n | |
* n = 250 | |
* n = 500 | |
* n = 1000 | |
* n = 2000 | |
==> passed | |
Test 8: call methods with invalid arguments | |
* n = 10, (row, col) = (-1, 5) | |
* n = 10, (row, col) = (11, 5) | |
* n = 10, (row, col) = (0, 5) | |
* n = 10, (row, col) = (5, -1) | |
* n = 10, (row, col) = (5, 11) | |
* n = 10, (row, col) = (5, 0) | |
* n = 10, (row, col) = (-2147483648, -2147483648) | |
* n = 10, (row, col) = (2147483647, 2147483647) | |
==> passed | |
Test 9: call constructor with invalid argument | |
* n = -10 | |
* n = -1 | |
* n = 0 | |
==> passed | |
Test 10: create multiple Percolation objects at the same time | |
(to make sure you didn't store data in static variables) | |
==> passed | |
Test 11: open predetermined list of sites using file inputs, | |
but permute the order in which methods are called | |
* filename = input8.txt; order = isFull(), isOpen(), percolates() | |
* filename = input8.txt; order = isFull(), percolates(), isOpen() | |
* filename = input8.txt; order = isOpen(), isFull(), percolates() | |
* filename = input8.txt; order = isOpen(), percolates(), isFull() | |
* filename = input8.txt; order = percolates(), isOpen(), isFull() | |
* filename = input8.txt; order = percolates(), isFull(), isOpen() | |
==> passed | |
Test 12: call open(), isOpen(), and numberOfOpenSites() | |
in random order until just before system percolates | |
* n = 3, trials = 40, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
* n = 5, trials = 20, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
* n = 7, trials = 10, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
* n = 10, trials = 5, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
* n = 20, trials = 2, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
* n = 50, trials = 1, p = (0.4, 0.4, 0.0, 0.0, 0.3) | |
==> passed | |
Test 13: call open() and percolates() in random order until just before system percolates | |
* n = 3, trials = 40, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
* n = 5, trials = 20, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
* n = 7, trials = 10, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
* n = 10, trials = 5, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
* n = 20, trials = 2, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
* n = 50, trials = 1, p = (0.5, 0.0, 0.0, 0.5, 0.0) | |
==> passed | |
Test 14: call open() and isFull() in random order until just before system percolates | |
* n = 3, trials = 40, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
* n = 5, trials = 20, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
* n = 7, trials = 10, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
* n = 10, trials = 5, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
* n = 20, trials = 2, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
* n = 50, trials = 1, p = (0.5, 0.0, 0.5, 0.0, 0.0) | |
==> passed | |
Test 15: call all methods in random order until just before system percolates | |
* n = 3, trials = 40, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
* n = 5, trials = 20, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
* n = 7, trials = 10, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
* n = 10, trials = 5, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
* n = 20, trials = 2, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
* n = 50, trials = 1, p = (0.2, 0.2, 0.2, 0.2, 0.2) | |
==> passed | |
Test 16: call all methods in random order until almost all sites are open | |
(with inputs not prone to backwash) | |
* n = 3 | |
* n = 5 | |
* n = 7 | |
* n = 10 | |
* n = 20 | |
* n = 50 | |
==> passed | |
Test 17: substitute WeightedQuickUnionUF data type that sets root nondeterministically; | |
call all methods in random order until almost all sites are open | |
(with inputs not prone to backwash) | |
* n = 3 | |
* n = 5 | |
* n = 7 | |
* n = 10 | |
* n = 20 | |
* n = 50 | |
==> passed | |
Test 18: check for backwash with predetermined sites | |
* filename = input20.txt | |
* filename = input10.txt | |
* filename = input50.txt | |
* filename = jerry47.txt | |
* filename = sedgewick60.txt | |
* filename = wayne98.txt | |
==> passed | |
Test 19: check for backwash with predetermined sites that have | |
multiple percolating paths | |
* filename = input3.txt | |
* filename = input4.txt | |
* filename = input7.txt | |
==> passed | |
Test 20: call all methods in random order until all sites are open | |
(these inputs are prone to backwash) | |
* n = 3 | |
* n = 5 | |
* n = 7 | |
* n = 10 | |
* n = 20 | |
* n = 50 | |
==> passed | |
Test 21: substitute WeightedQuickUnionUF data type that sets root nondeterministically; | |
call all methods in random order until all sites are open | |
(these inputs are prone to backwash) | |
* n = 3 | |
* n = 5 | |
* n = 7 | |
* n = 10 | |
* n = 20 | |
* n = 50 | |
==> passed | |
Total: 21/21 tests passed! | |
================================================================ | |
******************************************************************************** | |
* TESTING CORRECTNESS (substituting reference Percolation) | |
******************************************************************************** | |
Testing correctness of PercolationStats | |
*----------------------------------------------------------- | |
Running 17 total tests. | |
Test 1: check formatting of output of main() | |
% java-algs4 PercolationStats 20 10 | |
mean = 0.5747500000000001 | |
sttdev = 0.0456503924773198 | |
95% confidence interval = [0.5547428333673490, 0.5947571666326512] | |
- line 1 of output in student solution: | |
'sttdev = 0.0456503924773198 ' | |
- the required format is: | |
'stddev() = <double>' | |
% java-algs4 PercolationStats 200 100 | |
mean = 0.5923817499999999 | |
sttdev = 0.0081723317201977 | |
95% confidence interval = [0.5912491226092182, 0.5935143773907816] | |
- line 1 of output in student solution: | |
'sttdev = 0.0081723317201977 ' | |
- the required format is: | |
'stddev() = <double>' | |
==> FAILED | |
Test 2: check that methods in PercolationStats do not print to standard output | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 3: check that mean() returns value in expected range | |
* n = 2, trials = 10000 | |
* n = 5, trials = 10000 | |
* n = 10, trials = 10000 | |
* n = 25, trials = 10000 | |
==> passed | |
Test 4: check that stddev() returns value in expected range | |
* n = 2, trials = 10000 | |
* n = 5, trials = 10000 | |
* n = 10, trials = 10000 | |
* n = 25, trials = 10000 | |
==> passed | |
Test 5: check that PercolationStats constructor creates | |
trials Percolation objects, each of size n-by-n | |
* n = 15, trials = 15 | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 6: check that PercolationStats.main() creates | |
trials Percolation objects, each of size n-by-n | |
* n = 15, trials = 15 | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 7: check that PercolationStats calls open() until system percolates | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 8: check that PercolationStats does not call open() after system percolates | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 9: check that mean() is consistent with the number of intercepted calls to open() | |
on blocked sites | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 10: check that stddev() is consistent with the number of intercepted calls to open() | |
on blocked sites | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 11: check that confidenceLo() and confidenceHigh() are consistent with mean() and stddev() | |
* n = 20, trials = 10 | |
- PercolationStats confidence low = 0.5621864738891835 | |
- PercolationStats confidence high = 0.6003135261108163 | |
- PercolationStats mean = 0.5812499999999999 | |
- PercolationStats stddev = 0.04349728599451797 | |
- T = 10 | |
- student T = 10 | |
- mean - 1.96 * stddev / sqrt(T) = 0.5542901028274297 | |
- mean + 1.96 * stddev / sqrt(T) = 0.6082098971725701 | |
* n = 50, trials = 20 | |
- PercolationStats confidence low = 0.5707660802429328 | |
- PercolationStats confidence high = 0.5866339197570669 | |
- PercolationStats mean = 0.5786999999999999 | |
- PercolationStats stddev = 0.028623104395979794 | |
- T = 20 | |
- student T = 20 | |
- mean - 1.96 * stddev / sqrt(T) = 0.5661553713973291 | |
- mean + 1.96 * stddev / sqrt(T) = 0.5912446286026707 | |
* n = 100, trials = 50 | |
- PercolationStats confidence low = 0.5908420611695019 | |
- PercolationStats confidence high = 0.5973819388304983 | |
- PercolationStats mean = 0.5941120000000001 | |
- PercolationStats stddev = 0.016683361380092902 | |
- T = 50 | |
- student T = 50 | |
- mean - 1.96 * stddev / sqrt(T) = 0.5894876081577791 | |
- mean + 1.96 * stddev / sqrt(T) = 0.598736391842221 | |
* n = 64, trials = 150 | |
- PercolationStats confidence low = 0.5868394247987333 | |
- PercolationStats confidence high = 0.5965915647846 | |
- PercolationStats mean = 0.5917154947916666 | |
- PercolationStats stddev = 0.019902326501768482 | |
- T = 150 | |
- student T = 150 | |
- mean - 1.96 * stddev / sqrt(T) = 0.5885304592095912 | |
- mean + 1.96 * stddev / sqrt(T) = 0.594900530373742 | |
==> FAILED | |
Test 12: check that exception is thrown if either n or trials is out of bounds | |
* n = -23, trials = 42 | |
* n = 23, trials = 0 | |
* n = -42, trials = 0 | |
* n = 42, trials = -1 | |
* n = -2147483648, trials = -2147483648 | |
==> passed | |
Test 13: create two PercolationStats objects at the same time and check mean() | |
(to make sure you didn't store data in static variables) | |
* n1 = 50, trials1 = 10, n2 = 50, trials2 = 5 | |
* n1 = 50, trials1 = 5, n2 = 50, trials2 = 10 | |
* n1 = 50, trials1 = 10, n2 = 25, trials2 = 10 | |
* n1 = 25, trials1 = 10, n2 = 50, trials2 = 10 | |
* n1 = 50, trials1 = 10, n2 = 15, trials2 = 100 | |
* n1 = 15, trials1 = 100, n2 = 50, trials2 = 10 | |
==> passed | |
Test 14: check that the methods return the same value, regardless of | |
the order in which they are called | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 15: check that no calls to StdRandom.setSeed() | |
* n = 20, trials = 10 | |
* n = 20, trials = 10 | |
* n = 40, trials = 10 | |
* n = 80, trials = 10 | |
==> passed | |
Test 16: check distribution of number of sites opened until percolation | |
* n = 2, trials = 100000 | |
* n = 3, trials = 100000 | |
* n = 4, trials = 100000 | |
==> passed | |
Test 17: check that each site is opened the expected number of times | |
* n = 2, trials = 100000 | |
* n = 3, trials = 100000 | |
* n = 4, trials = 100000 | |
==> passed | |
Total: 15/17 tests passed! | |
================================================================ | |
******************************************************************************** | |
* MEMORY (substituting reference Percolation) | |
******************************************************************************** | |
Analyzing memory of PercolationStats | |
*----------------------------------------------------------- | |
Running 4 total tests. | |
Test 1a-1d: check memory usage as a function of T trials for n = 100 | |
(max allowed: 8*T + 128 bytes) | |
T bytes | |
-------------------------------------------- | |
=> passed 16 192 | |
=> passed 32 320 | |
=> passed 64 576 | |
=> passed 128 1088 | |
==> 4/4 tests passed | |
Estimated student memory = 8.00 T + 64.00 (R^2 = 1.000) | |
Total: 4/4 tests passed! | |
================================================================ | |
******************************************************************************** | |
* TIMING (substituting reference Percolation) | |
******************************************************************************** | |
Timing PercolationStats | |
*----------------------------------------------------------- | |
Running 4 total tests. | |
Test 1: Call PercolationStats constructor and instance methods and | |
count calls to StdStats.mean() and StdStats.stddev(). | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 2: Call PercolationStats constructor and instance methods and | |
count calls to methods in StdRandom. | |
* n = 20, trials = 10 | |
* n = 20, trials = 10 | |
* n = 40, trials = 10 | |
* n = 80, trials = 10 | |
==> passed | |
Test 3: Call PercolationStats constructor and instance methods and | |
count calls to methods in Percolation. | |
* n = 20, trials = 10 | |
* n = 50, trials = 20 | |
* n = 100, trials = 50 | |
* n = 64, trials = 150 | |
==> passed | |
Test 4: Call PercolationStats constructor and instance methods with trials = 3 | |
and values of n that go up by a multiplicative factor of sqrt(2). | |
The test passes when n reaches 2,896. | |
The approximate order-of-growth is n ^ (log ratio) | |
n seconds log ratio | |
------------------------ | |
724 0.14 2.3 | |
1024 0.32 2.4 | |
1448 0.81 2.7 | |
2048 1.99 2.6 | |
2896 4.56 2.4 | |
==> passed | |
Total: 4/4 tests passed! | |
================================================================ | |
******************************************************************************** | |
* MEMORY | |
******************************************************************************** | |
Analyzing memory of Percolation | |
*----------------------------------------------------------- | |
Running 4 total tests. | |
Test 1a-1d: check that total memory <= 17 n^2 + 128 n + 1024 bytes | |
n bytes | |
-------------------------------------------- | |
=> passed 64 69936 | |
=> passed 256 1114416 | |
=> passed 512 4456752 | |
=> passed 1024 17826096 | |
==> 4/4 tests passed | |
Estimated student memory = 17.00 n^2 + 0.00 n + 304.00 (R^2 = 1.000) | |
Test 2 (bonus): check that total memory <= 11 n^2 + 128 n + 1024 bytes | |
- failed memory test for n = 64 | |
==> FAILED | |
Total: 4/4 tests passed! | |
================================================================ | |
******************************************************************************** | |
* TIMING | |
******************************************************************************** | |
Timing Percolation | |
*----------------------------------------------------------- | |
Running 16 total tests. | |
Test 1a-1e: Creates an n-by-n percolation system; open sites at random until | |
the system percolates, interleaving calls to percolates() and open(). | |
Count calls to connected(), union() and find(). | |
2 * connected() | |
n union() + find() constructor | |
----------------------------------------------------------------------------------- | |
=> passed 16 282 272 2 | |
=> passed 32 1305 1158 2 | |
=> passed 64 5690 4800 2 | |
=> passed 128 23513 19592 2 | |
=> passed 256 92736 77982 2 | |
=> passed 512 369855 311216 2 | |
=> passed 1024 1467816 1240582 2 | |
==> 7/7 tests passed | |
If one of the values in the table violates the performance limits | |
the factor by which you failed the test appears in parentheses. | |
For example, (9.6x) in the union() column indicates that it uses | |
9.6x too many calls. | |
Tests 2a-2f: Check whether the number of calls to union(), connected(), and find() | |
is a constant per call to open(), isOpen(), isFull(), and percolates(). | |
The table shows the maximum number of union() and find() calls made | |
during a single call to open(), isOpen(), isFull(), and percolates(). | |
One call to connected() counts as two calls to find(). | |
n per open() per isOpen() per isFull() per percolates() | |
--------------------------------------------------------------------------------------------- | |
=> passed 16 8 0 2 2 | |
=> passed 32 8 0 2 2 | |
=> passed 64 8 0 2 2 | |
=> passed 128 8 0 2 2 | |
=> passed 256 8 0 2 2 | |
=> passed 512 8 0 2 2 | |
=> passed 1024 8 0 2 2 | |
==> 7/7 tests passed | |
Running time (in seconds) depends on the machine on which the script runs. | |
Test 3: Create an n-by-n percolation system; interleave calls to percolates() | |
and open() until the system percolates. The values of n go up by a | |
factor of sqrt(2). The test is passed if n >= 4096 in under 10 seconds. | |
The approximate order-of-growth is n ^ (log ratio) | |
log union-find log | |
n seconds ratio operations ratio | |
------------------------------------------- | |
1024 0.11 2.4 4190934 2.0 | |
1448 0.28 2.6 8388256 2.0 | |
2048 0.68 2.6 16751688 2.0 | |
2896 1.79 2.8 33529654 2.0 | |
4096 3.78 2.2 67001568 2.0 | |
==> passed | |
Test 4: Create an n-by-n percolation system; interleave calls to open(), | |
percolates(), isOpen(), isFull(), and numberOfOpenSites() until. | |
the system percolates. The values of n go up by a factor of sqrt(2). | |
The test is passed if n >= 4096 in under 10 seconds. | |
log union-find log | |
n seconds ratio operations ratio | |
------------------------------------------- | |
1024 0.11 1.9 4180368 2.0 | |
1448 0.29 2.9 8351516 2.0 | |
2048 0.87 3.2 16767330 2.0 | |
2896 1.92 2.3 33624770 2.0 | |
4096 4.15 2.2 67553946 2.0 | |
==> passed | |
Total: 16/16 tests passed! | |
================================================================ |
Percolation
##percolation - overview.
Welcome to the Percolation assignment. In this assignment, you will write a program to estimate the value of the percolation threshold via Monte Carlo simulation. In doing so, you will better understand depth-first-search, union-find structures, and the use of computer simulations for statistical inquiry.
Here is a printer friendly version of this assignment.
The code for this assignment is available through Snarf (using Ambient ), or the equivalent .jar can be downloaded from here .
You can also view/download the individual classes:
IPercolate.java
IUnionFind.java
PercolationDFS.java
PercolationStats.java
PercolationUF.java
PercolationVisualizer.java
QuickFind.java
###Acknowledgements
The assignment was developed by Kevin Wayne at Princeton University for their Computer Science 226 class.
###Introduction
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.)
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 has yet been derived.
###The Assignment Your task is to write a program to:
- Visualize the percolation process
- Estimate p* for a square grid percolation model
- Compare brute force (depth-first search) to union-find for finding connected open sites
You need to write code for the following classes:
PercolationDFS.java: This class implements the brute force method for percolation. Please refer to Section 2.4 in the Introduction to Programming in Java. You will complete the following methods:
- constructor: initialize a grid of size n
- open : open a particular grid cell
- isOpen & isFull : give current state of grid cell
- percolates and dfs : determine whether current grid will percolate by implementing recursive scheme depth-first search as discussed in class and the textbook
PercolationVisualizer.java: complete main so that it repeatedly calls a percolator (i.e., something that implements IPercolate like PercolationDFS ) to declare sites open, draw, and pause until the system percolates
PercolationUF.java: You will implement a more efficient solution that can use any union-find algorithm that implements IUnionFind (e.g., QuickFind.java ). You will complete the following methods:
- constructor: initialize a grid of size n and union-find algorithm
- open : open a particular grid cell and merge components as appropriate
- getIndex : return an index that uniquely identifies (row, col), so that each grid square can be in its own set at the beginning
- percolates : determine whether top and bottom are connected (i.e., in the same component)
QuickUWPC.java: A class that implements the weighted quick union with path compression data structure. See the Sedgewick & Wayne case study or the following reading for more information. You will need to create this file by adapting WeightedQuickUnionUF.java to implement the IUnionFind interface.
PercolationStats.java: A class that prompts for N and T , performs T experiments on an N x N grid, and prints the mean, standard deviation, and confidence interval of the percolation threshold, and timings of percolation simulations.
Get the Reddit app
A subreddit for all questions related to programming in any language.
Near beginner trying Coursera, lost on Percolation assignment. Is this concerning?
By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .
Enter the 6-digit code from your authenticator app
You’ve set up two-factor authentication for this account.
Enter a 6-digit backup code
Create your username and password.
Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.
Reset your password
Enter your email address or username and we’ll send you a link to reset your password
Check your inbox
An email with a link to reset your password was sent to the email address associated with your account
Choose a Reddit account to continue
import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF;
public class Percolation { // creates n-by-n grid, with all sites initially blocked public Percolation(int n) // opens the site (row, col) if it is not open already public void open(int row, int col) // is the site (row, col) open? public boolean isOpen(int row, int col) // is the site (row, col) full? public boolean isFull(int row, int col) // returns the number of open sites public int numberOfOpenSites() // does the system percolate? public boolean percolates() // unit testing (required) public static void main(String[] args) }
--> \[ \overline x = \frac{x_1 \, + \, x_2 \, + \, \cdots \, + \, x_{T}}{T}, \quad s^2 = \frac{(x_1 - \overline x )^2 \, + \, (x_2 - \overline x )^2 \,+\, \cdots \,+\, (x_{T} - \overline x )^2}{T-1} \]
--> \[ \left [ \overline x - \frac {1.96 s}{\sqrt{T}}, \;\; \overline x + \frac {1.96 s}{\sqrt{T}} \right] \]
public class PercolationStats { // perform independent trials on an n-by-n grid public PercolationStats(int n, int trials) // sample mean of percolation threshold public double mean() // sample standard deviation of percolation threshold public double stddev() // low endpoint of 95% confidence interval public double confidenceLow() // high endpoint of 95% confidence interval public double confidenceHigh() // test client (see below) public static void main(String[] args) }
% java-algs4 PercolationStats 200 100 mean() = 0.592993 stddev() = 0.008770 confidenceLow() = 0.591275 confidenceHigh() = 0.594712 elapsed time = 0.373 % java-algs4 PercolationStats 200 100 mean() = 0.592877 stddev() = 0.009991 confidenceLow() = 0.590919 confidenceHigh() = 0.594835 elapsed time = 0.364 % java-algs4 PercolationStats 2 100000 mean() = 0.666948 stddev() = 0.117752 confidenceLow() = 0.666218 confidenceHigh() = 0.667677 elapsed time = 0.087
IMAGES
COMMENTS
Testing correctness of Percolation *----- Running 15 total tests. Tests 1 through 8 create a Percolation object using your code, then repeatedly open sites by calling open(). After each call to open(), we check the return values of isOpen(i, j) for every (i, j), the return value of percolates(), and the return value of isFull(i, j) for every (i ...
Programming Assignments from coursera courses :). Contribute to moshensky/coursera development by creating an account on GitHub. ... Solutions By size. Enterprise Teams Startups By industry. Healthcare Financial services Manufacturing By use case. CI/CD & Automation DevOps ... / Assignment 1 Percolation / src / Percolation.java. Blame. Blame.
Princeton University: Algorithms, Part 1 Week 1 Percolation Programming Assignment Explanation | Coursera 📚You can learn more about this course here: https:...
Solution : https://drive.google.com/file/d/1ycCtEI2e4mZ5n0dEytaSf3H8Nuv2MGll/view#content #coursera #princetonuniversity #algorithm #youtube #solution
Assignment 1 - Percolation/ src ... (Assignment Solutions) Percolation. Finds the percolation threshold via Monte Carlo simulation. The percolation threshold is the probability needed for a cell to be open to almost guarantee that a system percolates. A system percolates if there is a connection between the top and bottom of the system.
Mastering the Percolation Assignment in Princeton's Algorithms, Part 1 • Mastering Percolation Assignment • Learn how to tackle the challenging Percolation A...
Programming Assignment 1: Percolation. Write a program to estimate the value of the percolation threshold via Monte Carlo simulation. Install our Java programming environment (optional). Install our custom IntelliJ programming environment by following these step-by-step instructions for your operating system [ Mac OS X · Windows · Linux ].
Programming Assignment 1: PercolationPr. gramming Assignment 1: PercolationWrite a program to estimate the value of the percolation thr. shold via Monte Carlo simulation.Insta. a Java programming environment. Install a Java programming environment on your computer by following these step by step instructions for your operating system [ Ma.
Test 1: check formatting of output of main () % java-algs4 PercolationStats 20 10. mean = 0.5747500000000001. sttdev = 0.0456503924773198. 95% confidence interval = [0.5547428333673490, 0.5947571666326512] - line 1 of output in student solution: 'sttdev = 0.0456503924773198 '.
For example, if sites are opened in a 20-by-20 grid 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. 50 open sites. 100 open sites. 150 open sites.
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 ...
Princeton University: Algorithm part 1 Week 1 Percolation Programming Assignment Solutions | CourseraDownload link of zip folder (Solutions) https://www.inst...
Percolation Assignment 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?
No mathematical solution for determining the percolation threshold has yet been derived. ###The Assignment Your task is to write a program to: Visualize the percolation process; Estimate p* for a square grid percolation model; Compare brute force (depth-first search) to union-find for finding connected open sites
Percolation Assignment. 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. We recommend (but do not require) these step-by-step instructions for Mac OS X , Windows , or Linux .
Percolation - 110 course points. The purpose of this assignment is to practice your understanding of the Union-Find data type and the 2D array data structure. Start your assignment early! You need time to understand the assignment and to answer the many questions that will arise as you read the description and the code provided.
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 ...
Algorithms, Part 1 is a solid course for IT or software engineers to learn algorithms which are provided by Princeton. Of course, we still have to take time to clarify the concepts after completing…
As suggested here I created my own percolation file starting from a solved nonogram . I have designed the bitmap image in Photoshop and created a class that converts the black and white BMP image to the TXT file format as accepted by the PercolationVisualizer provided as a testing tool for this assignment. Files can be found in /Percolation/src ...
Visualization client. PercolationVisualizer.java animates the results of opening sites in a percolation system specified by a file, performing the following steps: Read the grid size n from the file. Create an n -by- n grid of sites (initially all blocked). Read in a sequence of sites ( row, col) to open from the file.
Please be clear about what course and assignment you are talking about in future posts. I happen to know that this is a question about the Princeton course but many others who may be able to help you may not know what you are talking about. ... To check if there is percolation do the following: For each cell in the top row check if it is ...
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 ].
It is used 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 already public boolean isOpen(int i, int j) // is site (row i, column j) open?