Day 2: Fulminating Farmland
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Python
Here’s my initial solution in Python for part one.
import sys def distance(start, next): if start == next: return 6 sequence = "roygbv" startIndex = sequence.find(start) nextIndex = sequence.find(next, startIndex) if nextIndex >= 0: return nextIndex - startIndex else: return len(sequence) - startIndex + sequence.find(next) def total_distance(sequence): total = 0 lastChar = "r" for char in sequence: total += distance(lastChar, char) lastChar = char return total if __name__ == '__main__': print(total_distance(sys.argv[1]))C
Based this on other solutions posted here.
Usage:
$ gcc main.c $ ./a.out inputPart 1 solution
#include <stdio.h> int get_index(char c) { int index; switch (c) { case 'r': index = 0; break; case 'o': index = 1; break; case 'y': index = 2; break; case 'g': index = 3; break; case 'b': index = 4; break; case 'v': index = 5; break; } return index; } int main(int argc, char** argv) { int t[6][6] = { {6, 1, 2, 3, 4, 5}, {5, 6, 1, 2, 3, 4}, {4, 5, 6, 1, 2, 3}, {3, 4, 5, 6, 1, 2}, {2, 3, 4, 5, 6, 1}, {1, 2, 3, 4, 5, 6} }; FILE *fp = fopen(argv[1], "r"); int cur; int ch = 'r'; int next = get_index(ch); int dist = 0; while (true) { ch = fgetc(fp); if (ch == EOF || ch == '\n') break; cur = next; next = get_index(ch); dist += t[cur][next]; } fclose(fp); printf("Distance travelled is: %i\n", dist); return 0; }Tried to keep it as small as possible, so obvious issues like not checking argc and not checking for letters other than roygbv. Which is pretty cursed because index is uninitialised, so
get_indexreturns garbage, thent[cur][next]indexes into more garbage.Pretty standard for aoc to not check for invalid inputs, and just write just enough code to get the result. Indexing off into the weeds would be very frustrating to debug though if it didnt crash :D
Elixir
I thought about this a bit and realised that modulo math could probably help with this repeating pattern. So I transformed the letters to numbers, like on a clock. For part 2 I just sorted the program in descending order, since you start at 0 (or rather 6) and want to go as far as possible for all the remaining instructions.
solution
#!/usr/bin/env elixir require Logger defmodule AOC do def getProgNums(prog) do String.graphemes(prog) |> Enum.map( &Map.get(%{"r"=>6,"o"=>1,"y"=>2,"g"=>3,"b"=>4,"v"=>5}, &1, &1) ) end def part1(prog) do move(AOC.getProgNums(prog), 0, 0) end def move([], acc, _pos) do acc end def move([n | rest], acc, pos) do case rem(n-pos, 6) do r when r <= 0 -> move(rest, acc + r + 6, n) r -> move(rest, acc + r, n) end end def part2(prog) do AOC.getProgNums(prog) |> Enum.sort(:desc) |> move(0,0) end end # module Logger.info "Advent of Code 2026 Day 2" input = File.read!("input/day02.txt") |> String.trim() Logger.info "Part 1" inputTest0 = "obbvb" res = AOC.part1(inputTest0) if res != 16, do: raise "test result 0 is #{res} but should be 16" inputTest1 = "roygbv" res = AOC.part1(inputTest1) if res != 11, do: raise "test result 1 is #{res} but should be 11" inputTest2 = "vbgyor" res = AOC.part1(inputTest2) if res != 30, do: raise "test result 2 is #{res} but should be 30" inputTest3 = "vvvvvv" res = AOC.part1(inputTest3) if res != 35, do: raise "test result 3 is #{res} but should be 35" res = AOC.part1(input) Logger.info "answer: #{res}" Logger.info "Part 2" inputTest0 = "rybryb" res = AOC.part2(inputTest0) if res != 32, do: raise "test result 0 is #{res} but should be 32" inputTest1 = "vrvbvg" res = AOC.part2(inputTest1) if res != 33, do: raise "test result 1 is #{res} but should be 33" inputTest2 = "groovyyoyo" res = AOC.part2(inputTest2) if res != 55, do: raise "test result 2 is #{res} but should be 55" inputTest3 = "roygbvroygbvroygbv" res = AOC.part2(inputTest3) if res != 103, do: raise "test result 3 is #{res} but should be 103" res = AOC.part2(input) Logger.info "answer: #{res}"Hare
The first part wasn’t hard, I just had to check the maths twice. But I’ve spent way too much time on part 2 realizing that my function to find the optimal instruction iterated in reverse order, leading me to choose either a +6 move or the worst available one hehehe.
part 1
type waypoint = enum uint { red = 0, orange = 1, yellow = 2, green = 3, blue = 4, violet = 5, __modulo = 6, }; type state = struct { current: waypoint, distance: uint, }; fn u8_to_waypoint(c: u8) (waypoint | aoc::error) = { switch (c) { case 'r' => return waypoint::red; case 'o' => return waypoint::orange; case 'y' => return waypoint::yellow; case 'g' => return waypoint::green; case 'b' => return waypoint::blue; case 'v' => return waypoint::violet; case => return fmt::asprintf("Unknown input '{}'", c)!: aoc::error; }; }; fn goto_next(st: *state, w: waypoint) void = { if (st.current < w) { st.distance += w - st.current; } else { st.distance += waypoint::__modulo - st.current + w; }; st.current = w; }; fn part1(scan: *bufio::scanner) (int | aoc::error) = { let st = state { current = waypoint::red, distance = 0 }; const prgm = bufio::read_line(scan)!: []u8; for (let insn .. prgm) { goto_next(&st, u8_to_waypoint(insn)?); }; return st.distance: int; };part 2
fn waypoint_to_u8(w: waypoint) u8 = { switch (w) { case waypoint::red => return 'r'; case waypoint::orange => return 'o'; case waypoint::yellow => return 'y'; case waypoint::green => return 'g'; case waypoint::blue => return 'b'; case waypoint::violet => return 'v'; case => return 'a'; // unreachable }; }; fn next_wp(w: waypoint) waypoint = switch (w) { case waypoint::red => return waypoint::violet; case waypoint::orange => return waypoint::red; case waypoint::yellow => return waypoint::orange; case waypoint::green => return waypoint::yellow; case waypoint::blue => return waypoint::green; case waypoint::violet => return waypoint::blue; case waypoint::__modulo => return waypoint::__modulo; }; fn find_insn(w: waypoint, prgm: *[]u8) bool = { let insn = waypoint_to_u8(w); match (bytes::index(*prgm, insn)) { case void => return false; case let idx: size => const left = prgm[0..idx]; const right = prgm[idx+1..]; append(left, right...)!; *prgm = left; return true; }; }; fn goto_farthest(st: *state, prgm: *[]u8) void = { let best_insn = st.current; for (true) { if (find_insn(best_insn, prgm)) break; best_insn = next_wp(best_insn); }; goto_next(st, best_insn); }; fn part2(scan: *bufio::scanner) (int | aoc::error) = { let st = state { current = waypoint::red, distance = 0 }; let prgm = bufio::read_line(scan)!: []u8; for (len(prgm) > 0) { goto_farthest(&st, &prgm); }; return st.distance: int; };Lua
For part one I created a linked list of the colours, then pointed the “next” value of the last node to the first node, so that I could call
node.nextforever. Other people used mod which seems like a much more sensible solution. Oh well at least I learned about linked lists in lua!usage
lua robots.lua < inputPart1
Dots = "roygbv" function List.insert(node, value) node = {next = node, data = value} return node end function List.makeloop(head) local node = head local prev = nil while node do prev = node node = node.next end prev.next = head end function List.move(char, list) local incr = 0 local node = list if node.data == char then incr = 6 else while node.data ~= char do incr = incr + 1 node = node.next end end return incr, node end list = nil dist = 0 for i=#Dots,1,-1 do list = List.insert(list, Dots:sub(i,i)) end List.makeloop(list) local line = io.read("*line") for i=1,#line do incr, list = List.move(line:sub(i,i), list) dist = dist + incr end print(dist)For part 2 I just counted how many times each colour appeared, then printed them out in the correct order. I learned that iterating over a table in Lua using
pairs(table)is non-deterministic because it is a implemented using hashes, so I had to have another table to explicitly store the order.usage:
lua rearrange.lua < input | lua robot.luaPart2
local counts = {r=0, o=0, y=0, g=0, b=0, v=0} local order = {"r", "v", "b", "g", "y", "o"} local line = io.read("*line") for i = 1, #line do local char = line:sub(i, i) counts[char] = counts[char] + 1 end for _, key in ipairs(order) do for i = 1, counts[key] do io.write(key) end endI also learned a valuable lesson in version control when attempting to use
teeto debug and deleted my entire solution.Deleting your solution just means you get to rewrite it more optimally :)
Rust
fn parts(input: &str) -> (String, String) { let targets = input.chars().flat_map(|c| "_oygbvr".find(c)).collect_vec(); let part1 = 6 * targets .iter() .tuple_windows() .filter(|(a, b)| b <= a) .count() + targets.last().unwrap(); let part2 = targets.iter().min().unwrap() + 6 * (input.len() - 1); (part1.to_string(), part2.to_string()) }For part 1, I count the number of wrap-arounds as consecutive colors that are not increasing and check the last color to see where mod 6 it ends up. To make this work nicely, I moved the
rto the end of the colors and added a dummy color at the beginning, such that a singlerends up at 6.For part 2, the resulting program would always be a sorted list of colors, in the reverse order of my character list. Most characters will add 6 to the total. Only at the transition between color segments is the distance reduced, and the reduction corresponds exactly to the difference between the color values. Because the program must be sorted, the total reduction is the difference between the first and the last color. And since the sorting order would be the reverse of my character list, I end up with the inverse difference (mod 6) and add it instead of subtracting.
This is so satisfying. My code did pretty much the same thing at about 3 times the length haha. Well done!
That’s a pretty genius way to do it.
I just refactored my code and felt really smart about it, but now I’m sad again… Nice solution!
In the end I edited my solution to solve part 2 in the same way, but in the case that the input does not contain an ‘o’, it should be -4 instead of -5, since the difference between the first and last color would be 2 (and not 1). Similar for more missing letters. But as always the AOC inputs are (seemingly) made with the intent of not hitting such cases.
ArkScript.
(import aoc) (import std.Testing) (import std.List) (import std.String) (let dist (dict "r" 1 "o" 2 "y" 3 "g" 4 "b" 5 "v" 6)) (let solve (fun (data) { (mut output 0) (mut current "r") (list:forEach data (fun (waypoint) { (if (= waypoint current) (set output (+ output 6)) { (let diff (- (@ dist waypoint) (@ dist current))) (set current waypoint) (if (> diff 0) (set output (+ output diff)) (set output (+ output diff 6))) }) })) output })) (let optimize (fun (data) { (let counts (list:countOccurrences data)) (let new (list:fold "rvbgyo" "" (fun (acc next) (if (not (@ counts next)) acc (+ acc (string:repeat next (@ counts next))))))) (solve new) })) (let data (head (aoc:readLines "input.txt"))) (test:suite day2 { (test:case "part 1" { (test:eq (solve "obbvb") 16) (test:eq (solve "roygbv") 11) (test:eq (solve "vbgyor") 30) (test:eq (solve "vvvvvv") 35) (test:eq (solve data) 3681) }) (test:case "part 2" { (test:eq (optimize "rybryb") 32) (test:eq (optimize "rrbbyy") 32) (test:eq (optimize "vrvgvg") 33) (test:eq (optimize "groovyyoyo") 55) (test:eq (optimize "roygbvroygbvroygbv") 103) (test:eq (optimize data) 5935) })}) (if (> testing:_suite.failed 0) (sys:exit 1))TXR
(defun day02-pt1 () (let ((pgm (file-get-string "02-input")) (col-num (pairlis "roygbv" 1..7))) (cdr (reduce-left (tb ((pos . dist) nxpos) (cons nxpos (+ dist (wrap 1 6 (- nxpos pos))))) (map (lopip (assoc col-num) cdr) pgm) '(1 . 0)))))I didn’t solve part 2 programmatically. I simply used Emacs’
'count-matches'command to count occurrences of the 5 characters (not 6, as one of them never occurs!), and calculated the answer manually.Excel
https://docs.google.com/spreadsheets/d/1tP-TsXZ3LC4YnN7bsgm3LWI0uGSx8-2VUv4GaZzs8d4/edit?usp=sharing
See page 2, basically used the multiplication trick that u/mcmodknower identified.
Part 1 in excel is probably possible, especially as I did it via a lookup table anyway. Might give it a go later.
Edit: Part 1 is doable, not super hard, but didn’t do the lookup thing.
Rust
spoiler
const LOOKUP_TABLE: [[i32; 6]; 6] = [ [6, 1, 2, 3, 4, 5], [5, 6, 1, 2, 3, 4], [4, 5, 6, 1, 2, 3], [3, 4, 5, 6, 1, 2], [2, 3, 4, 5, 6, 1], [1, 2, 3, 4, 5, 6], ]; ... #[test] fn test_y2026_day2_part2() { let input = include_str!("../../input/2026/day_2.txt"); let input = include_str!("../../input/2026/day_2.txt"); let mut moves: Vec<u8> = input .trim() .chars() .map(|c| match c { 'r' => 6, 'o' => 1, 'y' => 2, 'g' => 3, 'b' => 4, 'v' => 5, _ => panic!(), }) .collect(); moves.sort(); let mut total = 0; let mut last = 0u8; moves.iter().rev().for_each(|next| { total += LOOKUP_TABLE[last as usize % 6][*next as usize % 6]; last = *next; }); println!("Total: {total}") }Suprisingly easy one this time as well. Part two probably could be optimised down to a simple multiplication i suspect, but no need when this is pretty damn fast anyway.
Rust
Solved part 2 simply by sorting the string appropriately and then calling part 1 again.
Solution
const fn color_to_n(color: u8) -> u8 { match color { b'r' => 0, b'o' => 1, b'y' => 2, b'g' => 3, b'b' => 4, b'v' => 5, _ => panic!("Unknown color"), } } fn distance(a: u8, b: u8) -> u8 { (5 + b - a) % 6 + 1 // Modulo with range from 1 to n instead of 0 to n-1 } fn part1(input: String) { let mut pos = 0; let mut dist = 0; for col in input.trim().bytes().map(color_to_n) { dist += u32::from(distance(pos, col)); pos = col; } println!("{dist}"); } fn part2(input: String) { let mut sorted = input.trim().as_bytes().to_owned(); sorted.sort_by_key(|&c| 6 - distance(0, color_to_n(c))); // Sort first r, then v, b, g, y, o part1(String::from_utf8(sorted).unwrap()); } util::aoc_main!();Uiua
Part one was simple enough, but part two was a little fiddlier to implement. I might have a think about whether there’s a tidier implementation. [edit: yes there was :-)]
Brief explanation
Both parts increment the index at each step and then consider the indexes of the various colours, mod 6. Part two could be even simpler:
-5×6⧻"rybryb"but that is probably so big a clue even in Uiua that it deserves to be spoilered.C ← "roygbv" S ← ∧(+◿6⊸˜-⊙+₁) S⊙0⋉C"obbvb" # Part 1 +1S⇌⍆◿6-1⊙0⋉C"rybryb" # Part 2Kotlin
I don’t know if I’ve ever seen an easier part 2 than today. If anything, I assume part 2 makes it possible to use the grouping counts from yesterday and do some smart maths with that, but I’m too sleepy to come up with that right now.
Code is just mapping the chars to ints for easier math (although now that I think about, I could’ve also just kept them as chars) and then counting the difference between chars following each other.
Edit: I’ve improved my
walk()method to be more Kotlin-like, but it does still “step” along the input:private fun walk(instructions: List<Char>) = (listOf(start) + instructions) .map { waypoints.indexOf(it) } .zipWithNext { a, b -> b - a } .sumOf { if (it == 0) waypoints.size else it.mod(waypoints.size) }Solution
class Day02 : Puzzle { private lateinit var instructions: List<Char> private val waypoints = charArrayOf('r', 'o', 'y', 'g', 'b', 'v') override fun readFile() { val input = readInputFromFile(2026, 2, false) instructions = input.lines().filter { it.isNotBlank() }.flatMap { it.toList() } } override fun solvePartOne(): String { return walk(instructions).toString() } override fun solvePartTwo(): String { return walk(instructions.sortedByDescending { if (it != 'r') waypoints.indexOf(it) else waypoints.size }).toString() } private fun walk(instructions: List<Char>): Long { val positions = instructions.map { waypoints.indexOf(it) } val first = positions.first() var sum = if (first > 0) first.toLong() else waypoints.size.toLong() for (pos in positions.indices) { if (pos == 0) continue val diff = positions[pos] - positions[pos - 1] sum += if (diff <= 0) { waypoints.size + diff } else { diff } } return sum } }full code on Codeberg
Rust
part 1 is finding the distance to the next char in a string, part 2 can be done with some simple math (result is about 6*input.len()).
Might update part 2 later with an even simpler version.
Solution
use std::{collections::HashMap, fs}; fn main() { let contents = fs::read_to_string("../../inputs/2026/2") .expect("Could not read input file"); // let contents = "rybryb"; let mut pos = 0; let w = "roygbvroygbv"; let l = w.len()/2; let mut counts: HashMap<char,i32> = HashMap::new(); for c in contents.lines().next().unwrap().chars() { let off = pos%l+1; // println!("{} {}", c, off); let p = w[off..].find(c).unwrap(); pos += p+1; counts.entry(c).and_modify(|e| *e += 1).or_insert(1); } println!("p1: {}", pos); let mut pos = 0; let mut d = 6; for c in "rvbgyo".chars() { let a = counts.get(&c).unwrap_or(&0); if *a == 0 { d-=1; continue; } pos += d; d = 5; pos += (a-1)*6; } println!("p2: {}", pos); }Crystal
Judging by other comments here there may be a better way to do part two
PATTERN = "roygbv".chars input = File.read("input.txt") p input.chars.unshift('r').each_cons_pair.sum {|p| dist p} # part 1 p find_longest input # part 2 def dist(chars : Tuple(Char, Char)) cur_i = PATTERN.index!(chars[0]) target_i = PATTERN.index!(chars[1]) return target_i - cur_i + (cur_i >= target_i ? 6 : 0) end def find_longest(input : String) available = input.chars.tally sum = 0 current = 'r' input.size.times do i = PATTERN.index!(current) (1..6).reverse_each do |j| next_way = PATTERN[(i + j) % 6] found = available.fetch next_way, 0 next if found <= 0 available[next_way] = found - 1 sum += j current = next_way break end end return sum end








