Fulminating Farmland

Published

December 2, 2026

library(mistlecode)

options(scipen = 999)

Part 1

I got much more tripped up by this than I expected. I have mistlecode::index() but it never does what I actually need which is that but with which(). I should just make it. However, I am quite pleased with my little bit of math for getting the correct distance anyways.

pattern <- c('r', 'o', 'y', 'g', 'b', 'v')
program <- 
  'input.txt' |>
  readLines() |>
  strsplit('') |>
  unlist()
step <- function(index = 1, current = 'r', distance = 0) {
  if (index == length(program) + 1) return(distance)
  nxt <- pattern[which(pattern == program[index])]
  if (current == nxt) {
    jump <- 6L
  } else {
    jump <- which(pattern == nxt) - which(pattern == current)
    if (jump < 0) jump <- 6 - abs(jump)
  }
  step(index + 1, nxt, distance + jump)
}
step()
[1] 3529

Part 2

This again took me far too long to figure out. I was trying some nonsense math-based solution using table() and eventually realized I could just make the program a factor() and sort() it to get everything set up then re-use the step() function from above. The levels are just starting with r and then whatever is a distance of 5 away (the farthest it can be without being itself).

program <- 
  'input.txt' |>
  readLines() |>
  strsplit('') |>
  unlist() |>
  factor(levels = c('r', 'v', 'b', 'g', 'y', 'o')) |> 
  sort()
step()
[1] 5815