Skip to content

Instantly share code, notes, and snippets.

@begriffs
Last active December 16, 2015 19:39
Show Gist options
  • Select an option

  • Save begriffs/5486492 to your computer and use it in GitHub Desktop.

Select an option

Save begriffs/5486492 to your computer and use it in GitHub Desktop.
Given a set (actually an array) and a symmetric relation (actually a boolean function), this divides the set into the equivalence classes of the reflexive and transitive closure of the relation.
function eq_classes(set, rel) {
var classes = {}, connected_stack, root,
stack_top, elt, pushed_more;
while(set.length > 0) {
root = set.shift();
classes[root] = [root];
connected_stack = [root];
while(connected_stack.length > 0) {
stack_top = connected_stack[connected_stack.length - 1];
pushed_more = false;
for(elt in set) {
if(rel(stack_top, set[elt])) {
pushed_more = true;
connected_stack.push(set[elt]);
classes[root].push(set[elt]);
set.splice(elt, 1);
}
}
if(!pushed_more) {
connected_stack.pop();
}
}
}
return classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment