generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
22.rs
274 lines (252 loc) · 7.99 KB
/
22.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use std::{
cmp::{Ordering, Reverse},
collections::{BinaryHeap, HashMap, HashSet},
};
advent_of_code::solution!(22);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Point {
x: usize,
y: usize,
z: usize,
}
impl Point {
fn from(v: Vec<usize>) -> Self {
Self {
x: v[0],
y: v[1],
z: v[2],
}
}
}
#[derive(Debug, Clone, Copy, Eq)]
struct Block {
key: usize,
start: Point,
end: Point,
}
impl Block {
fn from(s: &str, key: usize) -> Self {
let mut splits = s.split('~');
let start: Vec<_> = splits
.next()
.unwrap()
.split(',')
.map(|p| p.parse::<usize>().unwrap())
.collect();
let end: Vec<_> = splits
.next()
.unwrap()
.split(',')
.map(|p| p.parse::<usize>().unwrap())
.collect();
Self {
key,
start: Point::from(start),
end: Point::from(end),
}
}
fn lowest_z(&self) -> usize {
if self.start.z < self.end.z {
self.start.z
} else {
self.end.z
}
}
fn highest_z(&self) -> usize {
if self.start.z > self.end.z {
self.start.z
} else {
self.end.z
}
}
fn xy_intersect(&self, other: &Self) -> bool {
let x_overlap = self.start.x >= other.start.x && self.start.x <= other.end.x
|| self.start.x <= other.start.x && self.start.x >= other.end.x
|| self.end.x >= other.start.x && self.end.x <= other.end.x
|| self.end.x <= other.start.x && self.end.x >= other.end.x
|| other.start.x >= self.start.x && other.start.x <= self.end.x
|| other.start.x <= self.start.x && other.start.x >= self.end.x
|| other.end.x >= self.start.x && other.end.x <= self.end.x
|| other.end.x <= self.start.x && other.end.x >= self.end.x;
let y_overlap = self.start.y >= other.start.y && self.start.y <= other.end.y
|| self.start.y <= other.start.y && self.start.y >= other.end.y
|| self.end.y >= other.start.y && self.end.y <= other.end.y
|| self.end.y <= other.start.y && self.end.y >= other.end.y
|| other.start.y >= self.start.y && other.start.y <= self.end.y
|| other.start.y <= self.start.y && other.start.y >= self.end.y
|| other.end.y >= self.start.y && other.end.y <= self.end.y
|| other.end.y <= self.start.y && other.end.y >= self.end.y;
x_overlap && y_overlap
}
fn supports_at(&self, other: &Self) -> Option<usize> {
if self.highest_z() >= other.lowest_z() {
return None;
}
if self.xy_intersect(other) {
Some(self.highest_z() + 1)
} else {
None
}
}
fn lower_to(&mut self, new_z: usize) {
let diff = self.lowest_z() - new_z;
self.start.z -= diff;
self.end.z -= diff;
}
}
impl PartialOrd for Block {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Block {
fn cmp(&self, other: &Self) -> Ordering {
match self.lowest_z().cmp(&other.lowest_z()) {
Ordering::Greater => Ordering::Greater,
Ordering::Less => Ordering::Less,
Ordering::Equal => self.highest_z().cmp(&other.highest_z()),
}
}
}
impl PartialEq for Block {
fn eq(&self, other: &Self) -> bool {
self.lowest_z() == other.lowest_z()
}
}
fn drop_floating_blocks(blocks: Vec<Block>) -> (Vec<Block>, Vec<Vec<Block>>) {
let mut blocks = blocks;
let highest_possible = blocks[blocks.len() - 1].highest_z();
let mut tops: Vec<Vec<Block>> = vec![Vec::new(); highest_possible];
let mut max = highest_possible;
blocks.iter_mut().for_each(|b| {
if b.lowest_z() == 1 {
tops[b.highest_z()].push(*b);
} else {
let mut indices = (1..b.lowest_z()).rev();
let new_z = loop {
if let Some(i) = indices.next() {
if let Some(z) = tops[i].iter().find_map(|b2| b2.supports_at(b)) {
break z;
}
} else {
break 1;
}
};
b.lower_to(new_z);
tops[b.highest_z()].push(*b);
max = b.highest_z();
}
});
(blocks, tops[0..=max].to_vec())
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct BlockNode {
block: Block,
children: Vec<usize>,
parents: Vec<usize>,
}
fn build_tree(supports: Vec<Vec<Block>>) -> HashMap<usize, BlockNode> {
let mut map: HashMap<usize, BlockNode> = HashMap::new();
supports.iter().flatten().for_each(|block| {
let bottom = block.lowest_z();
let mut new_block = BlockNode {
block: *block,
children: Vec::new(),
parents: Vec::new(),
};
if bottom != 1 {
let v = &supports[bottom - 1];
v.iter().for_each(|supp_block| {
if supp_block.supports_at(&new_block.block).is_some() {
let supp_block = map
.get_mut(&supp_block.key)
.expect("Shouldn't hit any blocks not yet in map");
new_block.parents.push(supp_block.block.key);
supp_block.children.push(new_block.block.key);
}
})
}
map.insert(new_block.block.key, new_block);
});
map
}
fn find_max_weight(tree: &HashMap<usize, BlockNode>, start: usize) -> usize {
let mut pqueue = BinaryHeap::new();
let mut seen = HashSet::new();
let root = tree.get(&start).unwrap();
pqueue.push(Reverse(root));
seen.insert(start);
let mut count = 0;
let mut history = Vec::new();
while !pqueue.is_empty() {
let node = pqueue.pop().unwrap().0;
history.push(node.block.key);
node.children.iter().for_each(|n| {
if seen.contains(n) {
return;
}
let child = tree.get(n).unwrap();
if child.parents.iter().any(|pn| !seen.contains(pn)) {
return;
}
seen.insert(*n);
pqueue.push(Reverse(child));
count += 1;
})
}
count
}
pub fn part_one(input: &str) -> Option<u64> {
// step 1: Bring blocks down from floating
// step 2: Build dependency tree for blocks
// step 3: From bottom up, disintegrate any block which is not necessary to support other
// blocks
let mut blocks: Vec<_> = input
.lines()
.enumerate()
.map(|(i, s)| Block::from(s, i))
.collect();
blocks.sort();
let (_, supports) = drop_floating_blocks(blocks);
let tree = build_tree(supports);
let count = tree
.values()
.filter(|node| {
node.children.is_empty()
|| node.children.iter().all(|child| {
let child_node = tree.get(child).unwrap();
child_node.parents.len() > 1
})
})
.count();
Some(count as u64)
}
pub fn part_two(input: &str) -> Option<u64> {
let mut blocks: Vec<_> = input
.lines()
.enumerate()
.map(|(i, s)| Block::from(s, i))
.collect();
blocks.sort();
let (_, supports) = drop_floating_blocks(blocks);
let tree = build_tree(supports);
let results = tree
.values()
.map(|n| find_max_weight(&tree, n.block.key))
.collect::<Vec<usize>>();
Some(results.iter().sum::<usize>() as u64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(5));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(7));
}
}