Simplify day 08.
authorGreg Burri <greg.burri@gmail.com>
Sun, 8 Dec 2024 16:07:06 +0000 (17:07 +0100)
committerGreg Burri <greg.burri@gmail.com>
Sun, 8 Dec 2024 16:07:06 +0000 (17:07 +0100)
src/day08.rs

index 62f545b..1aec6bd 100644 (file)
@@ -35,6 +35,10 @@ pub enum AntinodeMode {
     Unlimited,
 }
 
+fn inside(p: (i32, i32), limits: (usize, usize)) -> bool {
+    p.0 >= 0 && p.0 < limits.0 as i32 && p.1 >= 0 && p.1 < limits.1 as i32
+}
+
 fn antinode_positions(
     pos: Vec<&(usize, usize)>,
     mode: &AntinodeMode,
@@ -47,32 +51,32 @@ fn antinode_positions(
         pos[1].1 as i32,
     );
     let (dx, dy) = (p1x - p2x, p1y - p2y);
+    let mut antinodes = Vec::new();
     match mode {
-        AntinodeMode::TwoPerPair => vec![(p1x + dx, p1y + dy), (p2x - dx, p2y - dy)],
+        AntinodeMode::TwoPerPair => {
+            let (a1, a2) = ((p1x + dx, p1y + dy), (p2x - dx, p2y - dy));
+            if inside(a1, limits) {
+                antinodes.push(a1);
+            }
+            if inside(a2, limits) {
+                antinodes.push(a2);
+            }
+        }
         AntinodeMode::Unlimited => {
-            let mut antinodes = Vec::new();
             let (mut current1, mut current2) = ((p1x, p1y), (p2x, p2y));
 
-            while current1.0 >= 0
-                && current1.0 < limits.0 as i32
-                && current1.1 >= 0
-                && current1.1 < limits.1 as i32
-            {
+            while inside(current1, limits) {
                 antinodes.push(current1);
                 current1 = (current1.0 + dx, current1.1 + dy);
             }
 
-            while current2.0 >= 0
-                && current2.0 < limits.0 as i32
-                && current2.1 >= 0
-                && current2.1 < limits.1 as i32
-            {
+            while inside(current2, limits) {
                 antinodes.push(current2);
                 current2 = (current2.0 - dx, current2.1 - dy);
             }
-            antinodes
         }
     }
+    antinodes
 }
 
 pub fn nb_antinodes(antennae: &Antennae, mode: AntinodeMode) -> i32 {
@@ -98,10 +102,6 @@ pub fn nb_antinodes(antennae: &Antennae, mode: AntinodeMode) -> i32 {
             .map(|positions| antinode_positions(positions, &mode, (nr, nc)))
             .flatten()
         {
-            if x < 0 || x >= nc as i32 || y < 0 || y >= nr as i32 {
-                continue;
-            }
-
             if !antinodes[(x as usize, y as usize)] {
                 antinodes[(x as usize, y as usize)] = true;
                 nb_antinodes += 1;