From 2f467ae7d783f2d0649a285dafab7d20018e6481 Mon Sep 17 00:00:00 2001 From: "max.nuding" Date: Fri, 9 Dec 2022 08:59:08 +0100 Subject: [PATCH] Improve follow_head function --- src/day09/mod.rs | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/src/day09/mod.rs b/src/day09/mod.rs index 34bc8e3..a258086 100644 --- a/src/day09/mod.rs +++ b/src/day09/mod.rs @@ -35,27 +35,15 @@ impl Position { } pub fn follow_head(&self, head: &Position) -> Self { - if head.x == self.x && head.y > self.y + 1 { - self.move_down() - } else if head.x == self.x && head.y < self.y - 1 { - self.move_up() - } else if head.x > self.x + 1 && head.y == self.y { - self.move_right() - } else if head.x < self.x - 1 && head.y == self.y { - self.move_left() - } else if (head.x - self.x).abs() == 1 && (head.y - self.y).abs() == 1 { - // One away diagonally - don't move + // Based on jenarvaezg/aoc2022 + // https://old.reddit.com/r/adventofcode/comments/zgnice/2022_day_9_solutions/izi6s4p/ + if self.x.abs_diff(head.x) < 2 && self.y.abs_diff(head.y) < 2 { self.clone() - } else if head.x < self.x && head.y < self.y { - self.move_left().move_up() - } else if head.x > self.x && head.y < self.y { - self.move_right().move_up() - } else if head.x > self.x && head.y > self.y { - self.move_right().move_down() - } else if head.x < self.x && head.y > self.y { - self.move_left().move_down() } else { - self.clone() + Self { + x: self.x + (head.x - self.x).signum(), + y: self.x + (head.y - self.y).signum(), + } } } }