|
| 1 | +advent_of_code::solution!(10); |
| 2 | + |
| 3 | +use advent_of_code::maneatingape::grid::*; |
| 4 | +use advent_of_code::maneatingape::hash::*; |
| 5 | +use advent_of_code::maneatingape::point::*; |
| 6 | + |
| 7 | +fn parse_data(input: &str) -> Grid<u8> { |
| 8 | + Grid::parse(input) |
| 9 | +} |
| 10 | + |
| 11 | +fn part_x(grid: &Grid<u8>) -> FastMap<(Point, Point), u32> { |
| 12 | + let mut start_positions = vec![]; |
| 13 | + for y in 0..grid.height { |
| 14 | + for x in 0..grid.width { |
| 15 | + if grid[Point::new(x, y)] == b'0' { |
| 16 | + start_positions.push(Point::new(x, y)); |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + let mut result = FastMap::new(); |
| 22 | + for start_position in start_positions { |
| 23 | + let mut paths = vec![(b'0', start_position)]; |
| 24 | + |
| 25 | + while let Some((height, location)) = paths.pop() { |
| 26 | + if height == b'9' { |
| 27 | + *result.entry((start_position, location)).or_insert(0) += 1; |
| 28 | + continue; |
| 29 | + } |
| 30 | + |
| 31 | + for step in [LEFT, RIGHT, UP, DOWN] { |
| 32 | + let next_location = location + step; |
| 33 | + if grid.contains(next_location) && grid[next_location] == height + 1 { |
| 34 | + paths.push((height + 1, next_location)); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + result |
| 41 | +} |
| 42 | + |
| 43 | +pub fn part_one(input: &str) -> Option<u32> { |
| 44 | + let grid = parse_data(input); |
| 45 | + |
| 46 | + let result = part_x(&grid).len() as u32; |
| 47 | + |
| 48 | + Some(result) |
| 49 | +} |
| 50 | + |
| 51 | +pub fn part_two(input: &str) -> Option<u32> { |
| 52 | + let grid = parse_data(input); |
| 53 | + |
| 54 | + let result = part_x(&grid).values().sum(); |
| 55 | + |
| 56 | + Some(result) |
| 57 | +} |
| 58 | + |
| 59 | +#[cfg(test)] |
| 60 | +mod tests { |
| 61 | + use super::*; |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn test_part_one() { |
| 65 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 66 | + assert_eq!(result, Some(36)); |
| 67 | + } |
| 68 | + |
| 69 | + #[test] |
| 70 | + fn test_part_two() { |
| 71 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 72 | + assert_eq!(result, Some(81)); |
| 73 | + } |
| 74 | +} |
0 commit comments