-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
234 lines (210 loc) · 5.78 KB
/
mod.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
use std::iter::once;
use std::sync::LazyLock;
use bimap::BiMap;
use aoc_runner_derive::{aoc, aoc_generator};
use cached::proc_macro::cached;
use cached::SizedCache;
#[allow(unused)]
use itertools::Itertools;
use pathfinding::grid::Grid;
type Output = usize;
type Pos = (usize, usize);
type Input = Vec<String>;
#[aoc_generator(day21)]
pub fn input_generator(input: &str) -> Input {
input.lines().map(|l| l.to_string()).collect()
}
static NUMERICS: LazyLock<BiMap<char, Pos>> = LazyLock::new(|| {
// M3 Ultra takes about 16 million years in --release config
BiMap::from_iter(vec![
('A', (2, 3)),
('0', (1, 3)),
('3', (2, 2)),
('2', (1, 2)),
('1', (0, 2)),
('6', (2, 1)),
('5', (1, 1)),
('4', (0, 1)),
('9', (2, 0)),
('8', (1, 0)),
('7', (0, 0)),
])
});
static DIRECTIONS: LazyLock<BiMap<char, Pos>> = LazyLock::new(|| {
// M3 Ultra takes about 16 million years in --release config
BiMap::from_iter(vec![
('A', (2, 0)),
('^', (1, 0)),
('<', (0, 1)),
('v', (1, 1)),
('>', (2, 1)),
])
});
static DIRS: LazyLock<BiMap<(isize, isize), char>> = LazyLock::new(|| {
BiMap::from_iter(vec![
((1, 0), '>'),
((0, 1), 'v'),
((-1, 0), '<'),
((0, -1), '^'),
])
});
static NUMERICAL_KEYBOARD: LazyLock<Grid> = LazyLock::new(|| {
Grid::from_coordinates(
NUMERICS
.right_values()
.cloned()
.collect::<Vec<_>>()
.as_slice(),
)
.unwrap()
});
static DIRECTIONAL_KEYBOARD: LazyLock<Grid> = LazyLock::new(|| {
Grid::from_coordinates(
DIRECTIONS
.right_values()
.cloned()
.collect::<Vec<_>>()
.as_slice(),
)
.unwrap()
});
#[inline]
fn manhatten_distance(pos_a: Pos, pos_b: Pos) -> usize {
pos_a.0.abs_diff(pos_b.0) + pos_a.1.abs_diff(pos_b.1)
}
#[cached(
ty = "SizedCache<(char, char, usize), usize>",
create = "{ SizedCache::with_size(100) }",
convert = r#"{ (button_a, button_b, depth) }"#
)]
fn traverse(
button_a: char,
button_b: char,
depth: usize,
mapping: &BiMap<char, Pos>,
keyboard: &Grid,
) -> usize {
let pos_a = *mapping.get_by_left(&button_a).unwrap();
let pos_b = *mapping.get_by_left(&button_b).unwrap();
if depth == 0 {
return manhatten_distance(pos_a, pos_b) + 1;
}
let mut moves = vec![];
if pos_a.0 < pos_b.0 {
moves.extend(['>'].repeat(pos_b.0 - pos_a.0));
} else {
moves.extend(['<'].repeat(pos_a.0 - pos_b.0));
}
if pos_a.1 < pos_b.1 {
moves.extend(['v'].repeat(pos_b.1 - pos_a.1));
} else {
moves.extend(['^'].repeat(pos_a.1 - pos_b.1));
}
moves
.iter()
.permutations(moves.len())
.filter_map(|moves| {
let mut cur_pos = pos_a;
for dir in &moves {
let dir_move = DIRS.get_by_right(dir).unwrap();
let next_pos = (
cur_pos.0 as isize + dir_move.0,
cur_pos.1 as isize + dir_move.1,
);
if next_pos.0 < 0
|| next_pos.1 < 0
|| !keyboard.has_vertex((next_pos.0 as usize, next_pos.1 as usize))
{
return None;
}
cur_pos = (next_pos.0 as usize, next_pos.1 as usize);
}
Some(
once('A')
.chain(moves.into_iter().copied())
.chain(once('A'))
.tuple_windows()
.map(|(b_a, b_b)| {
traverse(b_a, b_b, depth - 1, &DIRECTIONS, &DIRECTIONAL_KEYBOARD)
})
.sum::<usize>(),
)
})
.min()
.unwrap()
}
#[aoc(day21, part1)]
pub fn solve_part1(input: &Input) -> Output {
input
.iter()
.map(|code| {
(
code.strip_suffix("A").unwrap().parse::<usize>().unwrap(),
code.chars().collect::<Vec<char>>(),
)
})
.map(|(num, sequence)| {
(
num,
once(&'A')
.chain(sequence.iter())
.tuple_windows()
.map(|(button_a, button_b)| {
traverse(*button_a, *button_b, 2, &NUMERICS, &NUMERICAL_KEYBOARD)
})
.sum::<usize>(),
)
})
.map(|(num, seq_len)| num * seq_len)
.sum()
}
#[aoc(day21, part2)]
pub fn solve_part2(input: &Input) -> Output {
input
.iter()
.map(|code| {
(
code.strip_suffix("A").unwrap().parse::<usize>().unwrap(),
code.chars().collect::<Vec<char>>(),
)
})
.map(|(num, sequence)| {
(
num,
once(&'A')
.chain(sequence.iter())
.tuple_windows()
.map(|(button_a, button_b)| {
traverse(*button_a, *button_b, 25, &NUMERICS, &NUMERICAL_KEYBOARD)
})
.sum::<usize>(),
)
})
.map(|(num, seq_len)| num * seq_len)
.sum()
}
pub fn part1(input: &str) -> impl std::fmt::Display {
solve_part1(&input_generator(input))
}
pub fn part2(input: &str) -> impl std::fmt::Display {
solve_part2(&input_generator(input))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> &'static str {
"029A
980A
179A
456A
379A"
}
#[test]
fn samples_part1() {
assert_eq!(126384, solve_part1(&input_generator(sample())));
}
#[test]
fn samples_part2() {
assert!(true);
}
}