Question AkA doing weird rope physics!
You come across an old rope bridge and you are not sure it can hold your fat a** so you decide to model some rope physics to distract yourself (like that’s going to help…)
Directly from AoC
Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head.
We are given a series of moves to be done by the head, for example:
|
|
Parsing
Defining an Instruction
struct, each instruction has a direction L,R,U,D
and steps <number of steps to perform>
Iterating over our input we can map each line to our new instruction struct as follows
|
|
Part 1
We are asked to simulate the position of the tail after each instruction execution
We will treat both the head and tail as if they are starting from position 0,0
We know that the head should change its x
or y
value based on the current instruction direction.
Let’s create a struct to represent a Point and expose a method move
that mutates the point accordingly
|
|
Now lets start writing our solution for part 1
|
|
Next, adjust the tail point according to the head point
From the question description
Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both counts as touching):
As you can see, we need to “touch” the head at any point in time, or in other words, the distance between the points x
and y
cords is always less than 2
|
|
Armed with our new point structure we can implement the actual logic for part 1 We will use our SimpleSet from day 6 to keep track of the number of points the tail visited The size of that set will be the answer for this part
|
|
Part 2
Crap the rope just snaps and for some reason that does not make any sense we now have 10 knots to simulate… that’s what happens when you combine elves and rope physics.
At first glance, this seems complicated but in reality, we just need to think about the new requirements as an array of points where points[j]
is the tail of points[j+1]
and for each move adjust all tail
points according to their relative heads
|
|
Same as part one, we keep track of the points we visited using our SimpleSet
That’s it for today, see you tomorrow ⭐️
You can find the complete code here Thanks for reading!
This post is number 10 of a 13 posts series > Learning Go.