2022 Day 9

Posted on Dec 9, 2022

Part 1

Problem

General solution

Solution: Go

Our first attempt:

for mi := range moveInstructions {
    // Move the head
    head.x += moveInstructions[mi].DeltaX
    head.y += moveInstructions[mi].DeltaY

    // If the distance between the head and the tail is more than 1
    // across X or Y, move the tail 1 point in the opposite direction
    headTailDistanceX := head.x - tail.x
    headTailDistanceY := head.y - tail.y

    if headTailDistanceX < -1 {
        tail.x -= 1
    } else if headTailDistanceX > 1 {
        tail.x += 1
    }

    if headTailDistanceY < -1 {
        tail.y -= 1
    } else if headTailDistanceY > 1 {
        tail.y += 1
    }

    tailVisits[tail] = true

    fmt.Printf("%#v\n", head)
    fmt.Printf("%#v\n\n", tail)
}

This will cause the tail to move the absolute minimum required to be adjacent, including diagonal adjacency. However, whilst diagonal adjacency is considered to be touching, if the tail is not adjacent after the head has moved then the tail must move to be adjacent in the X or Y axis.

Part 2

Problem

General solution

Solution: Go

Post-solution thoughts