Skip to content

Commit 00a054a

Browse files
committed
Add solution for day 10
1 parent 67485a6 commit 00a054a

File tree

3 files changed

+80
-1
lines changed

3 files changed

+80
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.
3434
| [Day 7](./src/bin/07.rs) | `2.3ms` | `928.1ms` |
3535
| [Day 8](./src/bin/08.rs) | `39.3µs` | `85.2µs` |
3636
| [Day 9](./src/bin/09.rs) | `8.1ms` | `9.3ms` |
37+
| [Day 10](./src/bin/10.rs) | `1.6ms` | `1.4ms` |
3738

38-
**Total: 1044.82ms**
39+
**Total: 1047.82ms**
3940
<!--- benchmarking table --->
4041

4142
---

data/examples/10.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
89010123
2+
78121874
3+
87430965
4+
96549874
5+
45678903
6+
32019012
7+
01329801
8+
10456732

src/bin/10.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
use std::collections::HashSet;
2+
3+
advent_of_code::solution!(10);
4+
5+
pub fn solution<T>(input: &str) -> Option<u64>
6+
where T: FromIterator<(usize, usize)> + IntoIterator<Item = (usize, usize)> + Clone,
7+
8+
{
9+
let w = input.find('\n').unwrap() + 1;
10+
11+
let positions = input
12+
.chars()
13+
.enumerate()
14+
.filter_map(|(i, c)| match c {
15+
'.' | '\n' => None,
16+
_ => Some((c.to_digit(10).unwrap() as u8, (i % w, i / w))),
17+
})
18+
.fold(
19+
std::collections::HashMap::new(),
20+
|mut acc: std::collections::HashMap<u8, HashSet<_>>, (c, (x, y))| {
21+
acc.entry(c).or_default().insert((x, y));
22+
acc
23+
},
24+
);
25+
26+
let mut reachable: std::collections::HashMap<(usize, usize), T> = std::collections::HashMap::new();
27+
positions[&9].iter().for_each(|&(x, y)| {
28+
reachable.insert((x, y), T::from_iter([(x, y)]));
29+
});
30+
31+
for i in (0..=8).rev() {
32+
for &(x, y) in positions[&i].iter() {
33+
reachable.insert(
34+
(x, y),
35+
positions[&(i + 1)]
36+
.iter()
37+
.filter(|&&(nx, ny)| x.abs_diff(nx) + y.abs_diff(ny) == 1)
38+
.flat_map(|&(nx, ny)| reachable[&(nx, ny)].clone().into_iter())
39+
.collect(),
40+
);
41+
}
42+
}
43+
44+
Some(positions[&0].iter().map(|&(x, y)| reachable[&(x, y)].clone().into_iter().count() as u64).sum())
45+
}
46+
47+
pub fn part_one(input: &str) -> Option<u64> {
48+
solution::<HashSet<_>>(input)
49+
}
50+
51+
pub fn part_two(input: &str) -> Option<u64> {
52+
solution::<Vec<_>>(input)
53+
}
54+
55+
#[cfg(test)]
56+
mod tests {
57+
use super::*;
58+
59+
#[test]
60+
fn test_part_one() {
61+
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
62+
assert_eq!(result, Some(36));
63+
}
64+
65+
#[test]
66+
fn test_part_two() {
67+
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
68+
assert_eq!(result, Some(81));
69+
}
70+
}

0 commit comments

Comments
 (0)