Skip to content

Commit 4eb476f

Browse files
committed
stdlib: Modify union-find to guarantee that root nodes are always less than or equal to leaf nodes; add a "prune" method
1 parent 36c083b commit 4eb476f

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/lib/ufind.rs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import option::none;
22
import option::some;
33

44
// A very naive implementation of union-find with unsigned integer nodes.
5+
// Maintains the invariant that the root of a node is always equal to or less
6+
// than the node itself.
57

68
type node = option::t[uint];
79
type ufind = rec(mutable vec[mutable node] nodes);
@@ -20,18 +22,27 @@ fn make_set(&ufind ufnd) -> uint {
2022

2123
fn find(&ufind ufnd, uint n) -> uint {
2224
alt (ufnd.nodes.(n)) {
23-
case (none[uint]) { ret n; }
24-
case (some[uint](?m)) {
25-
// TODO: "be"
26-
ret find(ufnd, m);
27-
}
25+
case (none[uint]) { ret n; }
26+
case (some[uint](?m)) { be find(ufnd, m); }
2827
}
2928
}
3029

3130
fn union(&ufind ufnd, uint m, uint n) {
3231
auto m_root = find(ufnd, m);
3332
auto n_root = find(ufnd, n);
34-
auto ptr = some[uint](n_root);
35-
ufnd.nodes.(m_root) = ptr;
33+
if (m_root < n_root) {
34+
ufnd.nodes.(n_root) = some[uint](m_root);
35+
} else {
36+
ufnd.nodes.(m_root) = some[uint](n_root);
37+
}
38+
}
39+
40+
// Removes all sets with IDs greater than or equal to the given value.
41+
fn prune(&ufind ufnd, uint n) {
42+
// TODO: Use "slice" once we get rid of "mutable?"
43+
while (n != 0u) {
44+
vec::pop[node](ufnd.nodes);
45+
n -= 1u;
46+
}
3647
}
3748

0 commit comments

Comments
 (0)