From ba121691ba8812b17101e79221c63de754f05c05 Mon Sep 17 00:00:00 2001 From: MasterofJOKers Date: Sat, 24 Dec 2022 15:04:11 +0100 Subject: [PATCH] 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. --- day09/src/main.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/day09/src/main.rs b/day09/src/main.rs index 939fb78..3615ca1 100644 --- a/day09/src/main.rs +++ b/day09/src/main.rs @@ -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> { 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> { 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); + 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")?); + } if DEBUG { - h_pos.show(); - t_pos.show(); + knot_positions[0].show(); + knot_positions[9].show(); } - visited_locations.insert((t_pos.x.to_owned(), t_pos.y.to_owned())); + visited_locations.insert((knot_positions[9].x.to_owned(), knot_positions[9].y.to_owned())); } if DEBUG { println!("");