-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday20.rs
137 lines (130 loc) · 3.41 KB
/
day20.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
use itertools::Itertools;
use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
pub fn part1(data: &str) -> Option<usize> {
solve(data, 2, 100)
}
pub fn part2(data: &str) -> Option<usize> {
solve(data, 20, 100)
}
fn solve(data: &str, cheats: usize, time: usize) -> Option<usize> {
let lines = data.lines().collect::<Vec<_>>();
let start = lines
.iter()
.enumerate()
.flat_map(|(y, line)| {
line.bytes()
.enumerate()
.filter_map(move |(x, b)| Some((y, x)).filter(|_| b == b'S'))
})
.exactly_one()
.ok()?;
let mut path = vec![(start, 0)];
loop {
let prev = path.iter().nth_back(1).map(|(pos, _)| pos);
let (pos, b) = path
.last()
.iter()
.flat_map(|((y, x), _)| {
[
(y.wrapping_sub(1), *x),
(*y, x.wrapping_sub(1)),
(*y, x.wrapping_add(1)),
(y.wrapping_add(1), *x),
]
})
.map(|pos @ (y, x)| (pos, lines.get(y).map(|line| line.as_bytes().get(x))))
.filter(|(pos, b)| Some(pos) != prev && b != &Some(Some(&b'#')))
.exactly_one()
.ok()?;
path.push((pos, path.len()));
if b == Some(Some(&b'E')) {
break;
}
}
path.sort_unstable();
Some(
path.par_iter()
.enumerate()
.map(|(i, ((y1, x1), t1))| {
path[i + 1..]
.iter()
.take_while(|(pos, _)| *pos <= (y1 + cheats, *x1))
.filter(|((y2, x2), t2)| {
let d = y1.abs_diff(*y2) + x1.abs_diff(*x2);
d <= cheats && d + time <= t1.abs_diff(*t2)
})
.count()
})
.sum(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
use pretty_assertions::assert_eq;
static EXAMPLE: &str = indoc! {"
###############
#...#...#.....#
#.#.#.#.#.###.#
#S#...#.#.#...#
#######.#.#.###
#######.#.#...#
#######.#.###.#
###..E#...#...#
###.#######.###
#...###...#...#
#.#####.#.###.#
#.#...#.#.#...#
#.#.#.#.#.#.###
#...#...#...###
###############
"};
#[test]
fn part1_examples() {
[
(14, 2),
(14, 4),
(2, 6),
(4, 8),
(2, 10),
(3, 12),
(1, 20),
(1, 36),
(1, 38),
(1, 40),
(1, 64),
]
.into_iter()
.rev()
.fold(0, |acc, (count, time)| {
assert_eq!(Some(acc + count), solve(EXAMPLE, 2, time));
acc + count
});
}
#[test]
fn part2_examples() {
[
(32, 50),
(31, 52),
(29, 54),
(39, 56),
(25, 58),
(23, 60),
(20, 62),
(19, 64),
(12, 66),
(14, 68),
(12, 70),
(22, 72),
(4, 74),
(3, 76),
]
.into_iter()
.rev()
.fold(0, |acc, (count, time)| {
assert_eq!(Some(acc + count), solve(EXAMPLE, 20, time));
acc + count
});
}
}