tangled
alpha
login
or
join now
nove.dev
/
aoc-2025
1
fork
atom
:)
1
fork
atom
overview
issues
pulls
pipelines
union-find time
nove.dev
3 months ago
f753fc5b
f4183f26
+72
2 changed files
expand all
collapse all
unified
split
src
lib.rs
union_find.rs
+1
src/lib.rs
···
122
122
pub mod day7;
123
123
pub mod day8;
124
124
mod spatial;
125
125
+
mod union_find;
125
126
126
127
#[cfg(test)]
127
128
mod tests {
+71
src/union_find.rs
···
1
1
+
pub struct UnionFind<N> {
2
2
+
nodes: Vec<Node<N>>,
3
3
+
}
4
4
+
5
5
+
impl<N> Default for UnionFind<N> {
6
6
+
fn default() -> Self {
7
7
+
Self { nodes: vec![] }
8
8
+
}
9
9
+
}
10
10
+
11
11
+
impl<N> UnionFind<N>
12
12
+
where
13
13
+
N: Clone + PartialEq,
14
14
+
{
15
15
+
//returns a pointer to this element that can be used in union and find operations later
16
16
+
pub fn make_set(&mut self, element: N) -> usize {
17
17
+
let index = self.nodes.iter().enumerate().find(|(_, node)| node.inner == element);
18
18
+
if let Some(index) = index {
19
19
+
index.0
20
20
+
} else {
21
21
+
let new_node = Node {
22
22
+
parent: self.nodes.len(),
23
23
+
inner: element,
24
24
+
};
25
25
+
self.nodes.push(new_node);
26
26
+
self.nodes.len() - 1
27
27
+
}
28
28
+
}
29
29
+
30
30
+
/// operates on "pointers", which in this case are indexes into the internal vec
31
31
+
/// but can be considered opaque to a user
32
32
+
pub fn find(&mut self, element: usize) -> usize {
33
33
+
let root_index = self.root_index(element);
34
34
+
35
35
+
//take the opportunity to optimize??
36
36
+
let mut x_index;
37
37
+
let mut x_reference = &mut self.nodes[element];
38
38
+
39
39
+
while x_reference.parent != root_index {
40
40
+
let parent_index = x_reference.parent;
41
41
+
x_reference.parent = root_index;
42
42
+
x_index = parent_index;
43
43
+
x_reference = &mut self.nodes[x_index];
44
44
+
}
45
45
+
46
46
+
root_index
47
47
+
}
48
48
+
49
49
+
fn root_index(&self, element_index: usize) -> usize {
50
50
+
let mut root_index = element_index;
51
51
+
let mut root_reference = &self.nodes[root_index];
52
52
+
53
53
+
while root_reference.parent != root_index {
54
54
+
root_index = root_reference.parent;
55
55
+
root_reference = &self.nodes[root_index];
56
56
+
}
57
57
+
root_index
58
58
+
}
59
59
+
60
60
+
pub fn union(&mut self, elem1: usize, elem2: usize) {
61
61
+
todo!()
62
62
+
}
63
63
+
}
64
64
+
65
65
+
pub struct Node<N> {
66
66
+
//index into the vec of nodes contained within the data structure
67
67
+
//nodes are never removed or shifted within that vec
68
68
+
//root nodes point to themselves
69
69
+
parent: usize,
70
70
+
inner: N,
71
71
+
}