Skip to content

Instantly share code, notes, and snippets.

@adslaton
Created April 25, 2020 18:55
Show Gist options
  • Save adslaton/1cd1b727a78a97e39de7a02c5a8bf30f to your computer and use it in GitHub Desktop.
Save adslaton/1cd1b727a78a97e39de7a02c5a8bf30f to your computer and use it in GitHub Desktop.
quick-union-merge
const connections = new Map();
// create objects in the array
const uf = (n) => {
for (const x of Array(n).keys()) {
connections.set({ id: x, name: x}, x);
}
}
// root
uf.root = (n) => {
return connections.get(n);
}
// union
uf.union = (p, q) => {
const i = uf.root(p);
const j = uf.root(q);
if (i < j) {
connections.set(j, i);
} else {
connections.set(i, j);
}
};
// find
uf.connected = (p, q) => {
return (connections.get(p) === connections.get(q));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment