Created
February 11, 2013 05:49
-
-
Save keithrbennett/4752913 to your computer and use it in GitHub Desktop.
Dave Medinets' Algorithm Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.affy; | |
| public class Bug { | |
| private int[] id; | |
| public Bug(int n) { | |
| id = new int[n]; | |
| for (int i = 0; i < n; i++) { | |
| id[i] = i; | |
| } | |
| } | |
| private int root(int i) { | |
| while (i != id[i]) { | |
| i = id[i]; | |
| } | |
| return i; | |
| } | |
| public boolean connected(int p, int q) { | |
| return root(p) == root(q); | |
| } | |
| public void WorkingUnion(int p, int q) { | |
| System.out.println("Union " + p + " to " + q + ": "); | |
| int i = root(p); | |
| int j = root(q); | |
| id[j] = i; | |
| } | |
| public void BrokenUnion(int p, int q) { | |
| System.out.println("Union " + p + " to " + q + ": "); | |
| int i = root(p); | |
| int j = root(q); | |
| System.out.println("\t2assigning " + i + " to position " + j); | |
| System.out.println("X: " + toString()); | |
| id[j] = i; | |
| System.out.println("Y: " + toString()); | |
| } | |
| public String toString() { | |
| StringBuffer buffer = new StringBuffer("\t"); | |
| for (int i = 0; i < id.length; i++) { | |
| buffer.append(id[i]); | |
| buffer.append(", "); | |
| } | |
| return buffer.toString(); | |
| } | |
| public static void main(String[] args) { | |
| Bug o = new Bug(10); | |
| o.WorkingUnion(5, 1); | |
| o.WorkingUnion(5, 7); | |
| o.WorkingUnion(6, 3); | |
| o.WorkingUnion(0, 7); | |
| o.WorkingUnion(9, 4); | |
| o.BrokenUnion(4, 6); | |
| } | |
| } | |
| /* | |
| My output: | |
| Union 5 to 1: | |
| Union 5 to 7: | |
| Union 6 to 3: | |
| Union 0 to 7: | |
| Union 9 to 4: | |
| Union 4 to 6: | |
| 2assigning 9 to position 6 | |
| X: 0, 5, 2, 6, 9, 0, 6, 5, 8, 9, | |
| Y: 0, 5, 2, 6, 9, 0, 9, 5, 8, 9, | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment