rust/src/lib/UFind.rs
Marijn Haverbeke a3ec0b1f64 Rename std modules to be camelcased
(Have fun mergining your stuff with this.)
2011-05-06 22:51:19 +02:00

37 lines
834 B
Rust

import Option.none;
import Option.some;
// A very naive implementation of union-find with unsigned integer nodes.
type node = Option.t[uint];
type ufind = rec(mutable vec[mutable node] nodes);
fn make() -> ufind {
let vec[mutable node] v = vec(mutable none[uint]);
Vec.pop(v); // FIXME: botch
ret rec(mutable nodes=v);
}
fn make_set(&ufind ufnd) -> uint {
auto idx = Vec.len(ufnd.nodes);
ufnd.nodes += vec(mutable none[uint]);
ret idx;
}
fn find(&ufind ufnd, uint n) -> uint {
alt (ufnd.nodes.(n)) {
case (none[uint]) { ret n; }
case (some[uint](?m)) {
// TODO: "be"
ret find(ufnd, m);
}
}
}
fn union(&ufind ufnd, uint m, uint n) {
auto m_root = find(ufnd, m);
auto n_root = find(ufnd, n);
auto ptr = some[uint](n_root);
ufnd.nodes.(m_root) = ptr;
}