Skip to content

Commit afa6d85

Browse files
committed
stdlib: Add a simple union-find data structure
1 parent f28a9d8 commit afa6d85

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/lib/UFind.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import option.none;
2+
import option.some;
3+
4+
// A very naive implementation of union-find with unsigned integer nodes.
5+
6+
tag node {
7+
elem(uint, option.t[uint]);
8+
}
9+
type ufind = rec(mutable vec[mutable node] nodes);
10+
11+
fn make() -> ufind {
12+
let vec[mutable node] v = vec(mutable elem(0u, none[uint]));
13+
_vec.pop[mutable node](v); // FIXME: botch
14+
ret rec(mutable nodes=v);
15+
}
16+
17+
fn make_set(&ufind ufnd, uint n) {
18+
ufnd.nodes += vec(mutable elem(n, none[uint]));
19+
}
20+
21+
fn find(&ufind ufnd, uint n) -> uint {
22+
alt (ufnd.nodes.(n)) {
23+
case (elem(_, ?parent_opt)) {
24+
alt (parent_opt) {
25+
case (none[uint]) { ret n; }
26+
case (some[uint](?m)) {
27+
// TODO: "be"
28+
ret find(ufnd, m);
29+
}
30+
}
31+
}
32+
}
33+
}
34+
35+
fn union(&ufind ufnd, uint m, uint n) {
36+
auto m_root = find(ufnd, m);
37+
auto n_root = find(ufnd, n);
38+
auto ptr = some[uint](n_root);
39+
ufnd.nodes.(m_root) = elem(m_root, ptr);
40+
}
41+

src/lib/std.rc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ auth _str.pop_char = impure;
4747
auth _vec.shift = impure;
4848
auth _vec.unshift = impure;
4949
auth _vec.pop = impure;
50+
auth UFind.union = impure;
5051

5152
auth dbg = unsafe;
5253

@@ -81,6 +82,7 @@ mod bitv;
8182
mod sort;
8283
mod sha1;
8384
mod ebml;
85+
mod UFind;
8486

8587
// Local Variables:
8688
// mode: rust;

0 commit comments

Comments
 (0)