Permalink
Browse files

initial work on 'connected', and 'giant status'

  • Loading branch information...
davidreuss committed Feb 3, 2012
1 parent 45e1b0c commit 038b5daa8aa1e5e582ec7f83122f424b44b470be
Showing with 47 additions and 4 deletions.
  1. +25 −2 giantbook/GiantBook.java
  2. +22 −2 giantbook/WeightedQuickUnionUF.java
View
@@ -1,10 +1,33 @@
public class GiantBook {
+
+ private WeightedQuickUnionUF wqf;
+ private static boolean reachedGiantStatus = false;
- private int count;
+ private static int generateRandomNumber(int hi, int low) {
+ int random = StdRandom.uniform(hi, low);
+ // StdOut.println("Generated random number: " + random);
+ return random;
+ }
public static void main(String[] args) {
int count = StdIn.readInt();
- StdOut.println("I am a giant book, with " + count + " elements");
+ WeightedQuickUnionUF wqf = new WeightedQuickUnionUF(count);
+
+ while (wqf.count() != 1) {
+ wqf.union(
+ generateRandomNumber(0, count),
+ generateRandomNumber(0, count)
+ );
+
+ StdOut.print(".");
+
+ if (!reachedGiantStatus && wqf.isGiantComponentReached()) {
+ reachedGiantStatus = true;
+ StdOut.print("G");
+ }
+ }
+
+ StdOut.print("C\n");
}
}
@@ -11,9 +11,14 @@
private int[] id; // id[i] = parent of i
private int[] sz; // sz[i] = number of objects in subtree rooted at i
private int count; // number of components
+
+ private int total;
+
+ private boolean giantComponentReached = false;
// Create an empty union find data structure with N isolated sets.
public WeightedQuickUnionUF(int N) {
+ total = N;
count = N;
id = new int[N];
sz = new int[N];
@@ -22,6 +27,10 @@ public WeightedQuickUnionUF(int N) {
sz[i] = 1;
}
}
+
+ public boolean isGiantComponentReached() {
+ return giantComponentReached;
+ }
// Return the number of disjoint sets.
public int count() {
@@ -48,9 +57,20 @@ public void union(int p, int q) {
if (i == j) return;
// make smaller root point to larger one
- if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
- else { id[j] = i; sz[i] += sz[j]; }
+ if (sz[i] < sz[j]) {
+ id[i] = j;
+ sz[j] += sz[i];
+ } else {
+ id[j] = i;
+ sz[i] += sz[j];
+ }
count--;
+
+ if (!giantComponentReached) {
+ if (sz[i] >= total / 2) {
+ giantComponentReached = true;
+ }
+ }
}

0 comments on commit 038b5da

Please sign in to comment.