r/adventofcode • • 19h ago

SOLUTION MEGATHREAD -❄️- 2026 Day 2 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2026: The Advent Games

Today's Event: International Toboggan Championships

"Feel the rhythm, feel the rhyme, get on up, it's bobsled toboggan time!"
— Cool Runnings (1993)

Today's schedule possibly consists of:

  • Tracking Chute Runs and Team Practice
  • Embiggen is a perfectly cromulent word. Do with it as you will.
  • Qualifying Runs
  • Reverse code golf your solution
  • (oblig XKCD)
  • Second Runs and Finals
  • Why use few word when many word do trick?
  • Unnecessarily declare variables for everything and don't re-use variables
  • Use unnecessarily expensive functions and calls wherever possible
  • Implement redundant error checking everywhere
  • Javadocs >_>

Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!


--- Day 2: Fulminating Farmland ---


Post your code solution in this megathread.

25 Upvotes

580 comments sorted by

View all comments

2

u/flwyd 16h ago

[LANGUAGE: R] (on GitHub)

The approach: convert each character to a number from 1 to 6 (because R has 1-based array indices), and compute steps as (to - from - 1) mod 6 + 1: the minus and plus one get us six steps from a color to itself rather than 0. The walk function is an accumulator, adding the number of steps from the current color (cur mod 6) to the next color. Subtract 1 at the end, since we started at step 1 rather than step 0. In part 2, subtract 2 from each number mod 7 so that red becomes 6. Then sort descending so all the reds are first, then all violets, etc. Then add 2 mod 7 again to put everything back in its place. (Make sure you understand what your language's mod operator does: modulus and remainder behave differently on negative numbers.)

My theme this year is array languages, and this feels a bit like I’m stepping out of that mode: it looks more like functional programming than array programming, though the subtraction and modulus of an array by a scalar is nice. I had a lot of trouble figuring out how to get an in-order pairwise reduce-with-accumulator in Ivy; I’ll need to play around with some other array languages and see if I understand their model for reduce.

You could probably make part 2 O(n) by keeping a count of each color, then multiplying each count by 6, and adding the steps between each color. Watch out, though: my input is entirely missing one color.

part1 <- function(lines) {
  Reduce(walk, (parseinput(lines[1])), 1) - 1
}
part2 <- function(lines) {
  sorted <- (sort((parseinput(lines[1]) - 2) %% 7, decreasing = TRUE) + 2) %% 7
  Reduce(walk, sorted, 1) - 1
}
steps <- function(from, to) (to - from - 1) %% 6 + 1
walk <- function(cur, to) cur + steps(cur %% 6, to)
colors <- strsplit("roygbv", "")[[1]]
parseinput <- function(line) {
  lapply(strsplit(line, ""), function(x) match(x, colors))[[1]]
}