From: Greg Burri <greg.burri@gmail.com>
Date: Tue, 10 Dec 2024 17:11:40 +0000 (+0100)
Subject: Simplify and speed optimization
X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=81eda205e5fb20cdc0412f550da7d893a31b01de;p=advent_of_code_2024.git

Simplify and speed optimization
---

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<Position>) {
 }
 
 pub fn score(map: &Map, start_positions: &[Position], multiple_paths: bool) -> u32 {
-    fn neighbors((i, j): Position, ncols: usize, nrows: usize) -> Vec<Position> {
-        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<DMatrix<bool>>) -> 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()
         }
     }