Rename move functions, remove parameter

This commit is contained in:
max.nuding 2022-12-09 07:32:05 +01:00
parent 982dac721f
commit 1e9d553c22
Failed to extract signature

View File

@ -1,60 +1,60 @@
use crate::read;
use itertools::Itertools;
use std::collections::HashSet;
#[derive(Debug, PartialEq, Eq, Default, Clone, Copy, Hash)]
#[derive(Debug, PartialEq, Eq, Default, Clone, Hash)]
struct Position {
pub x: i32,
pub y: i32,
}
impl Position {
pub fn to_right(&self, count: i32) -> Self {
pub fn move_right(&self) -> Self {
Self {
x: self.x + count,
x: self.x + 1,
y: self.y,
}
}
pub fn to_left(&self, count: i32) -> Self {
pub fn move_left(&self) -> Self {
Self {
x: self.x - count,
x: self.x - 1,
y: self.y,
}
}
pub fn to_up(&self, count: i32) -> Self {
pub fn move_up(&self) -> Self {
Self {
x: self.x,
y: self.y - count,
y: self.y - 1,
}
}
pub fn to_down(&self, count: i32) -> Self {
pub fn move_down(&self) -> Self {
Self {
x: self.x,
y: self.y + count,
y: self.y + 1,
}
}
pub fn follow_head(&self, head: &Position) -> Self {
if head.x == self.x && head.y > self.y + 1 {
self.to_down(1)
self.move_down()
} else if head.x == self.x && head.y < self.y - 1 {
self.to_up(1)
self.move_up()
} else if head.x > self.x + 1 && head.y == self.y {
self.to_right(1)
self.move_right()
} else if head.x < self.x - 1 && head.y == self.y {
self.to_left(1)
self.move_left()
} else if (head.x - self.x).abs() == 1 && (head.y - self.y).abs() == 1 {
*self
// One away diagonally - don't move
self.clone()
} else if head.x < self.x && head.y < self.y {
self.to_left(1).to_up(1)
self.move_left().move_up()
} else if head.x > self.x && head.y < self.y {
self.to_right(1).to_up(1)
self.move_right().move_up()
} else if head.x > self.x && head.y > self.y {
self.to_right(1).to_down(1)
self.move_right().move_down()
} else if head.x < self.x && head.y > self.y {
self.to_left(1).to_down(1)
self.move_left().move_down()
} else {
*self
self.clone()
}
}
}
@ -84,17 +84,17 @@ pub fn simulate(num_knots: usize) -> usize {
let count = count.parse().unwrap();
for _c in 0..count {
knots[0] = match dir {
"R" => knots[0].to_right(1),
"U" => knots[0].to_up(1),
"L" => knots[0].to_left(1),
"D" => knots[0].to_down(1),
"R" => knots[0].move_right(),
"U" => knots[0].move_up(),
"L" => knots[0].move_left(),
"D" => knots[0].move_down(),
_ => unreachable!(),
};
for i in 1..knots.len() {
knots[i] = knots[i].follow_head(&knots[i - 1]);
}
visited.insert(*knots.last().unwrap());
visited.insert(knots.last().unwrap().clone());
}
}
visited.len()