Puzzle

Boxcar
; Day 2: Fulminating Farmland

[manifest example "obbvb"]
[manifest rainbow "roygbv"]
[manifest reverse "vbgyor"]
[manifest bouncy "vvvvvv"]
[manifest shuffled "rybryb"]
[manifest violets "vrvbvg"]
[manifest groovy "groovyyoyo"]
[manifest rainbows "roygbvroygbvroygbv"]

[manifest puzzle [include "input.txt"]]

[define colors "roygbv"]
[define program [train input [trim] [chars]]]

; The color of the waypoint at `pos`, as an index into `colors`.
;
; The robot starts on red and the colors repeat every 6 waypoints.
[define color-at [fn [pos] [mod pos 6]]]

; How far it is from a waypoint of color `from` to the next waypoint of color
; `to` (both indices into `colors`): between 1 and 6.
[define distance [fn [from to] [+ 1 [mod [- to from 1] 6]]]]

; Handles one move of the robot.
;
; `pos` is the robot's current position.
; `c` is the color of the next waypoint to go to.
;
; Starting from 0, the final `pos` is the total distance traveled.
[define step
  [fn [pos c] [+ pos [distance [color-at pos] [index-of colors c]]]]]

[part 1
  [train program [fold step 0]]
  [expect example 16]
  [expect rainbow 11]
  [expect reverse 30]
  [expect bouncy 35]
  [expect puzzle 3790]]

[part 2
  ; How far the robot moves for each instruction, from each color it can be on:
  ;
  ;     +--------+-------------+
  ;     |     to | r o y g b v |
  ;     +--------+-------------+
  ;     | from r | 6 1 2 3 4 5 |
  ;     | from o | 5 6 1 2 3 4 |
  ;     | from y | 4 5 6 1 2 3 |
  ;     | from g | 3 4 5 6 1 2 |
  ;     | from b | 2 3 4 5 6 1 |
  ;     | from v | 1 2 3 4 5 6 |
  ;     +--------+-------------+
  ;
  ; The longest possible move from any color is to that same color again (6).
  ;
  ; So to pick the longest route, we start by visiting all of the reds, then all
  ; of the violets, then all of the blues, and so on.
  ;
  ; The rearranged program is just the original sorted into the order "rvbgyo".
  [train program [sort-by [fn [c] [index-of "rvbgyo" c]]] [fold step 0]]
  [expect shuffled 32]
  [expect violets 33]
  [expect groovy 55]
  [expect rainbows 103]
  [expect puzzle 6409]]