From 3bd6fc260082176ec7fbd97f7b00f72ead760265 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Tue, 10 Dec 2024 09:43:02 -0600 Subject: [PATCH] Day 10 part 2 --- 2024/rust/src/day10.rs | 47 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/2024/rust/src/day10.rs b/2024/rust/src/day10.rs index 671b211..46a6f66 100644 --- a/2024/rust/src/day10.rs +++ b/2024/rust/src/day10.rs @@ -17,7 +17,7 @@ fn part1(input: &str) -> usize { for (x, height) in row.iter().enumerate() { let mut scores = HashSet::new(); if *height == 0 { - find_paths_to_nines(&map, *height, x, y, &mut scores); + capture_scores(&map, *height, x, y, &mut scores); sum += scores.len(); } println!("{x} {y} {height}"); @@ -26,7 +26,7 @@ fn part1(input: &str) -> usize { sum } -fn find_paths_to_nines( +fn capture_scores( map: &Vec>, height: u8, x: usize, @@ -49,13 +49,50 @@ fn find_paths_to_nines( let next_height = map[ny][nx]; if next_height.saturating_sub(height) == 1 { println!("{height} -> {next_height} at {nx},{ny}"); - find_paths_to_nines(map, next_height, nx, ny, scores) + capture_scores(map, next_height, nx, ny, scores) } } } fn part2(input: &str) -> usize { - 0 + println!("{input}"); + let mut sum = 0; + let map: Vec> = input + .lines() + .map(|l| l.bytes().map(|b| b - b'0').collect()) + .collect(); + for (y, row) in map.iter().enumerate() { + for (x, height) in row.iter().enumerate() { + if *height == 0 { + sum += find_paths_to_nines(&map, *height, x, y); + } + println!("{x} {y} {height}"); + } + } + sum +} + +fn find_paths_to_nines(map: &Vec>, height: u8, x: usize, y: usize) -> usize { + let mut sum = 0; + if height == 9 { + return 1; + } + for (nx, ny) in [ + (x + 1, y), + (x.saturating_sub(1), y), + (x, y + 1), + (x, y.saturating_sub(1)), + ] { + if nx >= map[0].len() || ny >= map.len() { + continue; + } + let next_height = map[ny][nx]; + if next_height.saturating_sub(height) == 1 { + println!("{height} -> {next_height} at {nx},{ny}"); + sum += find_paths_to_nines(map, next_height, nx, ny) + } + } + sum } #[cfg(test)] @@ -73,6 +110,6 @@ mod tests { 01329801 10456732"#; assert_eq!(part1(input), 36); - assert_eq!(part2(input), 0); + assert_eq!(part2(input), 81); } }