This one was fun. I had a bit of a puzzle trying to figure out why my code wasn’t working on the test examples. Turns out indigo was missing from “roygbv”. At least the off-by-sometimes-one error wasn’t in my code.

Part 1

Just the straightforward lookup of the distances as we go.

function get_dist(waypoints)
    dist = Dict{Tuple{Char,Char},Int}()

    n = length(waypoints)

    for (start_idx, char) in enumerate(waypoints), dd = 1:n
        end_char = waypoints[mod1(start_idx + dd, n)]
        dist[char, end_char] = dd
    end

    return dist
end

function part1(fname = "input.txt", waypoints = "roygbv")
    instructions = readline(fname)

    dist = get_dist(waypoints)

    position = 'r'
    total_distance = 0
    for ii in instructions
        total_distance += dist[position, ii]
        position = ii
    end

    return total_distance
end

Part 2

The greedy approach is all we need. Keep the destination the same until you run out and then just maximize the difference.

function part2(fname = "input.txt", waypoints = "roygbv")
    instructions = readline(fname)

    dist = get_dist(waypoints)

    total_distance = 6 * length(instructions)

    position = 'r'
    remaining = Set(instructions)
    while true
        delete!(remaining, position)
        isempty(remaining) && break

        new_position = argmax(kk -> dist[position, kk], remaining)
        total_distance -= 6 - dist[position, new_position]
        position = new_position
    end

    return total_distance
end