-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_15.rs
115 lines (94 loc) · 2.62 KB
/
day_15.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
use std::collections::BinaryHeap;
use hashbrown::HashMap;
use nd_vec::{vector, Vector};
use aoc_lib::{direction::cardinal::Direction, matrix::Grid};
use common::{solution, Answer};
solution!("Chiton", 15);
type Point = Vector<usize, 2>;
fn part_a(input: &str) -> Answer {
let matrix = Grid::parse(input, |chr| chr.to_digit(10).unwrap() as u8);
solve(matrix.size, |pos| matrix.get(pos).copied()).into()
}
fn part_b(input: &str) -> Answer {
let matrix = Grid::parse(input, |chr| chr.to_digit(10).unwrap() as u8);
solve(matrix.size * 5, |pos| {
let (cx, cy) = (pos.x() / matrix.size.x(), pos.y() / matrix.size.y());
if cx > 4 || cy > 4 {
return None;
};
let pos = vector!(pos.x() % matrix.size.x(), pos.y() % matrix.size.y());
matrix
.get(pos)
.map(|x| (x + cx as u8 + cy as u8 - 1) % 9 + 1)
})
.into()
}
fn solve(size: Point, get: impl Fn(Point) -> Option<u8>) -> u32 {
let mut seen = HashMap::new();
let mut queue = BinaryHeap::new();
seen.insert(vector!(0, 0), 0);
queue.push(QueueItem {
pos: vector!(0, 0),
distance: 0,
});
while let Some(item) = queue.pop() {
if item.pos == size - vector!(1, 1) {
return item.distance;
}
for dir in Direction::ALL {
let Some((pos, cost)) = dir.try_advance(item.pos).and_then(|x| Some((x, get(x)?)))
else {
continue;
};
let dist = seen.entry(pos).or_insert(u32::MAX);
let next_dist = item.distance + cost as u32;
if next_dist < *dist {
*dist = next_dist;
queue.push(QueueItem {
pos,
distance: next_dist,
});
}
}
}
unreachable!()
}
#[derive(PartialEq, Eq)]
struct QueueItem {
pos: Point,
distance: u32,
}
impl Ord for QueueItem {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.distance.cmp(&self.distance)
}
}
impl PartialOrd for QueueItem {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 40.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 315.into());
}
}