Function aoc::y22d09::y22d09

source ·
pub fn y22d09(input: &str, number_of_knots: u32) -> u32
Expand description

The solution for the day nine challenge.

We expect the input as a string and the number of knots in the rope (as described above the minimum number of knots is 2).

We start by initializing a vector that contains tuples of coordinates for each knot in the rope; each knot starts at coordinates (0, 0). We also add the starting position to the visited set. Then we loop over the instructions (lines). We do the following process x times where x is the number of moves that the instruction specified. We loop through all of the knots and if we’re on the first knot then we apply the specified move. Then for every knot except the actual tail knot (and including the head knot) we need to reconcile the position of the knot directly following the current knot. As described in the challenge prompt the two knots must always be touching (including diagonally) which amounts to doing some simple checks on the positions of the two knots and adjusting the tail knot accordingly. If we’re on the final (tail) knot then we just need to insert it’s current position into the set. Finally, after looping through all of the instructions we can return the length of the set to get our answer.

§Example

// probably read this from the input file...
let input = "U 2\nR 2\nU 2\nD 3\nL 4";
assert_eq!(y22d09(input, 3), 4);