AoC 2022 D9: Rope Bridge
| Problem statement | Source code | Tags: Grid walking
← Previous Back to AoC Index Next →
Part 1
We have a tail that's always following the head, and we need to record the positions of the tail. Naturally we'd like to fold over the list of moves, tracking the current positions of the head and tail as well as the set of tail positions.
The movement itself is done recursively over the number of steps. If we have no more steps to take, return the state as-is.
Otherwise, we move the head one step in the given direction, and then move the tail.
(By the way, I defined |+| and |-| for 2D vector arithmetic so I don't have to load Data.Vector.)
In moveTail, we check the distance between the head and tail. If it's more than 1 in either direction, we need to move the tail one step towards the head.
Part 2
Now with 10 knots, we just need to upgrade the state to a collection of 10 positions. Most of the logic is the same, except I now use mapAccumL to move each knot in turn, keeping track of the previous knot's position. Conveniently, this also returns the tail position so we can add it to the set.