Skip to content

Instantly share code, notes, and snippets.

@catalyst0
Created January 23, 2022 04:09
Show Gist options
  • Save catalyst0/1aeffdac49138c3e1787c9962e2cb1f0 to your computer and use it in GitHub Desktop.
Save catalyst0/1aeffdac49138c3e1787c9962e2cb1f0 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
public class ConnectJoinAlgorithm {
static int[] id;
static int[] integers;
static int N = 10;
public static void main(String[] args) {
id = new int[N];
integers = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
// Copy the id array to a new integers array; intergers[] stores the values we are connecting and tracking
System.arraycopy(id, 0, integers, 0, N);
// Print initial id array before any connections are made
System.out.println(Arrays.toString(id));
System.out.println(find(4, 9)); // 4 and 9 have not been connected; this should evaulate to false
connect(4, 3);
System.out.println(Arrays.toString(id));
connect(8, 3);
System.out.println(Arrays.toString(id));
System.out.println(find(3, 8)); // Since we connected 3 and 8 this should evaluate to true
System.out.println(find(4, 8)); // Since we connected 4 and 8 via 3 this should evaluate to true
}
public static boolean find (int p, int q) {
return (id[p] == id[q]);
}
public static void connect(int p, int q) {
int idp = id[p];
int idq = id[q];
for (int i = 0; i < N; i++) {
if (id[i] == idp) {
id[i] = idq;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment