|
| 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