Last active
December 16, 2015 19:39
-
-
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.
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
| 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