Advent of Code 2026: Day 02

In reply to Advent of Code 2026: Day 01

A little bit trickier today!

Part 1:

Now that we have all our thingamajigs and gizmos from Day 1, it's time to do some farming! We come across some elves who are tinkering with a robot that follows a rainbow of waypoints 🌈 (such as roygbv ). Every robot starts at red (r) and has a series of instructions that sees it travelling forward to the next waypoint of that instruction's colour.

So instructions of ryvv will see the robot travel 2 places to yellow (y) , then 2 more to violet (v) but then 6 more places to the next violet (v) waypoint. The elves want to know how far a robot will go given some program.

def part1(input)
  program = input.first.split("")
  waypoints = %w[r o y g b v]
  count_distance(program, waypoints, "r")
end

def count_distance(program, waypoints, starting_waypoint)
  prev_waypoint = starting_waypoint
  program.map do |nxt|
    res = waypoints.rotate(waypoints.index(prev_waypoint)).index(nxt)
    prev_waypoint = nxt
  res.zero? ? 6 : res
  end.inject(:+)
end

⭐️ Rather creating a massive list of a repeating roygbv sequence, we can take the static set of waypoints, and use Ruby's rotate to have the list start from whichever waypoint we want, then count the number of moves from the start of the list.

So, if we have [r o y g b v] , and we are currently at y , but want to know how many moves to o , we could do:

  • [r o y g b v].rotate(2) #=> [y g b v r o] where 2 is the index of y

  • [y g b v r o].index("o") #=> 5 asking for the index of o will give us the number of moves we need to make to get to it.

  • If we need to go from one waypoint to the same waypoint e.g. from r to r , that would be 6 moves, but index() would return 0, so we replace any zero results with 6.

Part 2:

The elves want to go far, but they can't type a new program, they can only re-arrange an existing one! So our job is to take a program, and re-arrange it such that the robot will go the furthest with every move.

e.g. if we have [r y b r y b] we could re-arrange that to [r r b b y y] so the robot moves 6, 5, 6, 4, 6 spaces with each move.

⭐️ Here we can simply sort our instructions based on their distance from our starting node, and then from each other. So once we have exhausted all our 6 moves from r to r, we can move 5 spaces to the next furthest node, and then move 6 from b to b and so on.

long_program = program.sort_by { |insn| waypoints.index(insn).zero? ? 6 : waypoints.index(insn) }.reverse
count_distance(long_program, waypoints, "r")