Simplification
authorGreg Burri <greg.burri@gmail.com>
Fri, 9 Dec 2022 15:39:58 +0000 (16:39 +0100)
committerGreg Burri <greg.burri@gmail.com>
Fri, 9 Dec 2022 15:39:58 +0000 (16:39 +0100)
src/day09.rs

index 193d7cb..0fedd3c 100644 (file)
@@ -48,24 +48,17 @@ pub fn nb_positions_visited_by_tail<const N: usize>(movements: &[Movement]) -> u
             // 2) Move the rest of the rope.
             for i in (0..N-1).rev() {
                 let target = rope[i+1];
-                let mut node = rope[i];
+                let node = &mut rope[i];
 
-                let (dx, dy): (i32, i32) = (node.0 - target.0, node.1 - target.1);
-                let (dx_abs, dy_abs) = (dx.abs(), dy.abs());
+                let (dx, dy): (i32, i32) = (target.0 - node.0, target.1 - node.1);
 
-                if dx_abs == 2 && dy_abs == 2 {
-                    node = (target.0 + dx.signum(), target.1 + dy.signum());
-                } else if dx_abs >= 2 {
-                    node = (target.0 + dx.signum(), target.1);
-                } else if dy_abs >= 2 {
-                    node = (target.0, target.1 + dy.signum());
+                if dx.abs() >= 2 || dy.abs() >= 2 {
+                    node.0 += dx.signum();
+                    node.1 += dy.signum();
+                    if i == 0 {
+                        visited.insert(*node);
+                    }
                 }
-
-                if i == 0 && node != rope[i] {
-                    visited.insert(node);
-                }
-
-                rope[i] = node;
             }
         }
     };