day09: Chage stuff for part 2

Part 1 was missing the "y_diff.abs() == x_diff.abs()" condition in
Pos.move_after(), which made the program show the wrong output at first.
This commit is contained in:
MasterofJOKers 2022-12-24 15:04:11 +01:00
parent ae6ac6979a
commit ba121691ba
1 changed files with 17 additions and 9 deletions

View File

@ -40,7 +40,9 @@ impl Pos {
return
}
if x_diff.abs() > y_diff.abs() {
if x_diff.abs() == y_diff.abs() {
self.move_((x_diff.abs() - 1) * x_diff.signum(), (y_diff.abs() - 1) * y_diff.signum());
} else if x_diff.abs() > y_diff.abs() {
self.move_((x_diff.abs() - 1) * x_diff.signum(), y_diff);
} else {
self.move_(x_diff, (y_diff.abs() - 1) * y_diff.signum());
@ -56,8 +58,11 @@ fn main() -> Result<(), Box<dyn error::Error>> {
let f = File::open("input.txt")?;
let reader = BufReader::new(f);
let mut h_pos = Pos { x: 0, y: 0 };
let mut t_pos = Pos { x: 0, y: 0 };
let mut knot_positions = vec![];
for _ in 0..10 {
knot_positions.push(Pos { x: 0, y: 0 });
}
let mut visited_locations = HashSet::new();
for line in reader.lines() {
let line = line?;
@ -65,13 +70,16 @@ fn main() -> Result<(), Box<dyn error::Error>> {
let direction = s_iter.next().ok_or(format!("Could not split {line} on whitespace"))?;
let amount: i32 = s_iter.next().ok_or(format!("Could not split {line} into 2 parts."))?.parse()?;
for _ in 0..amount {
h_pos.move_into_direction(direction)?;
t_pos.move_after(&h_pos);
if DEBUG {
h_pos.show();
t_pos.show();
knot_positions[0].move_into_direction(direction)?;
for i in 1..knot_positions.len() {
let (head, tail) = knot_positions.split_at_mut(i);
tail[0].move_after(head.last().ok_or("head doesn't have an element")?);
}
visited_locations.insert((t_pos.x.to_owned(), t_pos.y.to_owned()));
if DEBUG {
knot_positions[0].show();
knot_positions[9].show();
}
visited_locations.insert((knot_positions[9].x.to_owned(), knot_positions[9].y.to_owned()));
}
if DEBUG {
println!("");