Improve follow_head function

This commit is contained in:
max.nuding 2022-12-09 08:59:08 +01:00
parent fe66170e3e
commit 2f467ae7d7
Failed to extract signature

View File

@ -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(),
}
}
}
}