From 81eda205e5fb20cdc0412f550da7d893a31b01de Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 10 Dec 2024 18:11:40 +0100 Subject: [PATCH] Simplify and speed optimization --- src/day10.rs | 42 +++++++++++++++--------------------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/src/day10.rs b/src/day10.rs index 961e73f..43dd221 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -29,23 +29,6 @@ pub fn read_map(reader: &mut dyn BufRead) -> (Map, Vec) { } pub fn score(map: &Map, start_positions: &[Position], multiple_paths: bool) -> u32 { - fn neighbors((i, j): Position, ncols: usize, nrows: usize) -> Vec { - let mut positions = Vec::new(); - if i > 0 { - positions.push((i - 1, j)); - } - if i < nrows - 1 { - positions.push((i + 1, j)); - } - if j > 0 { - positions.push((i, j - 1)); - } - if j < ncols - 1 { - positions.push((i, j + 1)); - } - positions - } - fn get_nb_summits((i, j): Position, map: &Map, visited: &mut Option>) -> u32 { if let Some(visited) = visited.as_mut() { if visited[(i, j)] { @@ -58,16 +41,21 @@ pub fn score(map: &Map, start_positions: &[Position], multiple_paths: bool) -> u if map[(i, j)] == 9 { 1 } else { - neighbors((i, j), map.ncols(), map.nrows()) - .into_iter() - .map(|(i2, j2)| { - if map[(i2, j2)] == map[(i, j)] + 1 { - get_nb_summits((i2, j2), map, visited) - } else { - 0 - } - }) - .sum() + [ + (i.wrapping_sub(1), j), + (i + 1, j), + (i, j.wrapping_sub(1)), + (i, j + 1), + ] + .into_iter() + .map(|(i2, j2)| { + if i2 < map.nrows() && j2 < map.ncols() && map[(i2, j2)] == map[(i, j)] + 1 { + get_nb_summits((i2, j2), map, visited) + } else { + 0 + } + }) + .sum() } } -- 2.45.2