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