summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorReiner Herrmann <reiner@reiner-h.de>2024-12-12 16:24:41 +0100
committerReiner Herrmann <reiner@reiner-h.de>2024-12-12 16:24:41 +0100
commit97f5266304a9d380907bdde21cd0c880d93e4144 (patch)
treef3acf27d0e02d719fc2cb0ff5e07fe7e15da15f2
parent222f452d5cbb51f7f3492a2c488e40d52a47ea5b (diff)
day10 solution 2
-rw-r--r--src/bin/day10.rs26
1 files changed, 25 insertions, 1 deletions
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::<Vec<_>>();
assert_eq!(Map::new(&input).trailhead_score(), 36);
+ assert_eq!(Map::new(&input).distinct_trails(), 81);
}
}