Skip to content

Instantly share code, notes, and snippets.

@Trimad
Last active May 12, 2022 01:54
Show Gist options
  • Save Trimad/b4ef64f9780bb7d313a3ef09ed7bf95e to your computer and use it in GitHub Desktop.
Save Trimad/b4ef64f9780bb7d313a3ef09ed7bf95e to your computer and use it in GitHub Desktop.
Kruskal_Processing
import java.util.Collections;
import java.util.Comparator;
final int N_NODES = 128;
int nodeCount = 0;
ArrayList<Node> nodes = new ArrayList();
ArrayList<Edge> edges = new ArrayList();
ArrayList<Edge> mst = new ArrayList();
void setup() {
size(1024, 1024);
background(0);
for (int i = 0; i < N_NODES; i++) {
nodes.add(new Node(int(random(16, width-16)), int(random(16, height-16))));
}
MSTKruskal(nodes);
for (Edge e : edges) {
stroke(255, 10);
e.draw();
}
for (Edge e : mst) {
stroke(255);
e.draw();
}
for (Node n : nodes) {
stroke(255);
strokeWeight(8);
n.draw();
}
noLoop();
saveFrame("kruskal.png");
}
void MSTKruskal(ArrayList<Node> nodes) {
for (Node a : nodes) {
for (Node b : nodes) {
if (a.id < b.id)
edges.add(new Edge(a, b));
}
}
DisjointSet grouping = new DisjointSet(edges.size());
Collections.sort(edges);
for (Edge e : edges) {
if (grouping.find(e.a.id) != grouping.find(e.b.id)) {
mst.add(new Edge(e.a, e.b));
grouping.union(e.a.id, e.b.id);
}
}
}
class DisjointSet {
int parent[];
DisjointSet(int size) {
parent = new int[size];
for (int i = 0; i < size; i++)
parent[i] = i;
}
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]); // path compression
return parent[x];
}
void union(int x, int y) {
parent[find(x)] = find(y);
}
}
class Node {
float x, y;
int id;
Node(int x, int y) {
this.x = x;
this.y = y;
this.id = nodeCount++;
}
void draw() {
point(this.x,this.y);
}
}
public class Edge implements Comparable<Edge> {
float distSq;
Node a, b;
Edge(Node a, Node b) {
this.a = a;
this.b = b;
float dx = a.x - b.x;
float dy = a.y - b.y;
distSq = dx * dx + dy * dy;
}
@Override
public int compareTo(Edge _e) {
if (this.distSq > _e.distSq) {
return 1;
} else if (this.distSq < _e.distSq) {
return -1;
} else {
return 0;
}
}
void draw() {
line(this.a.x, this.a.y, this.b.x, this.b.y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment