From 97f5266304a9d380907bdde21cd0c880d93e4144 Mon Sep 17 00:00:00 2001 From: Reiner Herrmann Date: Thu, 12 Dec 2024 16:24:41 +0100 Subject: day10 solution 2 --- src/bin/day10.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/bin/day10.rs b/src/bin/day10.rs index d7c80b3..3a1547e 100644 --- a/src/bin/day10.rs +++ b/src/bin/day10.rs @@ -5,7 +5,7 @@ static DAY: u8 = 10; fn main() { let input = advent::read_lines(DAY); println!("{DAY}a: {}", Map::new(&input).trailhead_score()); - println!("{DAY}b: {}", 0); + println!("{DAY}b: {}", Map::new(&input).distinct_trails()); } #[derive(Eq, PartialEq, Hash, Copy, Clone)] @@ -58,11 +58,34 @@ impl Map { peaks } + fn count_trails(&self, pos: &Position) -> usize { + let height = *self.map.get(pos).unwrap(); + if height == 9 { + return 1; + } + let mut trails = 0; + for (x, y) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { + let neighbor = Position { x: pos.x + x, y: pos.y + y }; + if let Some(height_neighbor) = self.map.get(&neighbor) { + if *height_neighbor == height + 1 { + trails += self.count_trails(&neighbor); + } + } + } + trails + } + fn trailhead_score(&self) -> usize { self.trailheads().iter() .map(|trailhead| self.reachable_peaks(trailhead).len()) .sum() } + + fn distinct_trails(&self) -> usize { + self.trailheads().iter() + .map(|trailhead| self.count_trails(trailhead)) + .sum() + } } #[cfg(test)] @@ -82,5 +105,6 @@ mod tests { "10456732", ].iter().map(|&x| String::from(x)).collect::>(); assert_eq!(Map::new(&input).trailhead_score(), 36); + assert_eq!(Map::new(&input).distinct_trails(), 81); } } -- cgit v1.2.3