Day 4: Perilous Pier
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
Haskell
After some juggling to combine foldM and zipWithM ended up with quite a concise solution:
{-# LANGUAGE OverloadedStrings #-} import Control.Arrow import Control.Monad import Data.List import Data.Maybe import Data.Text qualified as T import Data.Text.IO qualified as TIO findPatternLength w = find (pattern w) [1 ..] pattern w l = isJust $ foldM (zipWithM merge) (T.unpack $ T.replicate l "?") chunks where chunks = T.unpack <$> T.chunksOf l w merge a b | a == b = Just a | a == '?' = Just b | b == '?' = Just a | otherwise = Nothing part1 = fmap sum . mapM findPatternLength part2 = findPatternLength . T.concat main :: IO () main = TIO.getContents >>= print . (part1 &&& part2) . T.linesAt first I wondered why you used
Maybeinstead ofandwhen you check forisJustat the end anyways. I got it eventually, it’s for short-circuiting when merging does fail and to update the pattern while folding.
Python
Simply try every code length successively until we find a match
click to view code
def min_code_length(s: str): n = len(s) # try every code length successively for i in range(1, n+1): # extract code code = list(s[:i]) # iterate over barcode to see if valid j = 0 for ch in s: if ch == code[j]: # we match the code pass elif ch == '?': # the barcode has a '?' which can be skipped pass elif code[j] == '?': # our code has a '?' which can be collapsed to the char we need code[j] = ch else: # code does not match barcode break j = (j+1) % i else: # no-break: we matched the entire barcode successfully return i assert min_code_length("rgbrgbrgbr") == 3 assert min_code_length("?rv") == 2 assert min_code_length("o??v???y") == 5 assert min_code_length("??bg?v??") == 4 assert min_code_length("??b?????") == 1 assert min_code_length("??b?????") == 1 # part1: try each barcode separately def part1(data: str): total = 0 for barcode in data.splitlines(): total += min_code_length(barcode) return total assert part1("""rgbrgbrgbr ?rv o??v???y ??bg?v?? ??b????? ???""") == 16 # part2: combine entire barcode def part2(data: str): return min_code_length(data.replace('\n','')) assert part2("""rro?? ?g ?g??? ??r????? ??g? ?? yy?v?o ???v b?g?? ?y??v?or ????r?o ?? ????? ?r??v?r""") == 16Python
Didn’t really expect to reuse part one solution as is for part two, but it worked way better that I expected.
Is it good – maybe not; did the snake language solve it in tens of milliseconds – it most certainly did.
The code snippet only includes solution code, for the full repo (plumbing code) see the link in the header.
from collections.abc import Iterable from enum import StrEnum from common import Mode, read_file class Color(StrEnum): Missing = '?' Red = 'r' Orange = 'o' Yellow = 'y' Green = 'g' Blue = 'b' Violet = 'v' _barcode = list[Color] _barcodes = Iterable[_barcode] def part_1(barcodes: _barcodes) -> None: print(sum(_find_minimum(b) for b in barcodes)) def part_2(barcodes: _barcodes) -> None: print(_find_minimum([*b for b in barcodes])) def read(mode: Mode) -> _barcodes: for line in read_file(4, mode): if not line: continue yield [Color(c) for c in line] def solve(mode: Mode, second: bool) -> None: data = read(mode) if second: part_2(data) else: part_1(data) def _check_length(barcode: _barcode, length: int) -> bool: candidate = barcode[:length] start = 0 for step in range(len(barcode) // length): start = step * length for index_candidate in range(length): index_barcode = start + index_candidate if barcode[index_barcode] == Color.Missing: continue if candidate[index_candidate] == Color.Missing: candidate[index_candidate] = barcode[index_barcode] continue if candidate[index_candidate] != barcode[index_barcode]: return False start += length for index_candidate in range(len(barcode) % length): index_barcode = start + index_candidate if barcode[index_barcode] == Color.Missing: continue if candidate[index_candidate] == Color.Missing: candidate[index_candidate] = barcode[index_barcode] continue if candidate[index_candidate] != barcode[index_barcode]: return False return True def _find_minimum(barcode: _barcode) -> int: minimum_length = max(1, len({c for c in barcode if c != Color.Missing})) for length in range(minimum_length, len(barcode)): if _check_length(barcode, length): return length return len(barcode)Elixir
Hmm, my solution (although not really clean) works for the test input but not for the real input (answer is too low). Also looked around for some more codes to test but it works for those too. Anyone got additional tips what to try?
My approach is to first disassemble each code and then with increasing instruction length check for each legible character if there are any interference with this length, both looking ahead and behind. After that I take the minimum length where that didn’t result in collisions.
code
#!/usr/bin/env elixir defmodule AOC do def part1(input) do input |> Enum.map(&AOC.check/1) |> Enum.sum() end def check(code) do chars = String.graphemes(code) |> Enum.with_index |> Enum.group_by(fn {c,_} -> c end, fn {_,i} -> i end) codeLen = String.length(code) illegibPos = case Map.get(chars, "?") do nil -> [] other -> other end legibChars = case Map.drop(chars, ["?"]) do nil -> %{} other -> other end keys = Map.keys(legibChars) case legibChars do lC when (keys == []) -> 1 _ -> length(Map.keys(legibChars))..codeLen |> Enum.map( fn instrLen -> case checkChars(legibChars, illegibPos, codeLen, instrLen) do s when s < 0 -> 99 _ -> instrLen end end ) |> Enum.min() end end def checkChars(legibChars, illegibPos, codeLen, instrLen) do Enum.map(Map.keys(legibChars), fn c -> Enum.map(legibChars[c], fn p -> d = if p + instrLen >= codeLen do -instrLen else instrLen end if p+d in legibChars[c] or p+d in illegibPos or p+d < 0 do 1 else -99 end end ) |> Enum.sum() end ) |> Enum.sum() end end # module input = File.read!("input/day04.txt") |> String.split("\n", trim: true) testInput = """ rgbrgbrgbr ?rv o??v???y ??bg?v?? ??b????? ??? """ |> String.split("\n", trim: true) res = AOC.part1(testInput) if res != 16, do: raise "test input is #{res} but should be 16" res = AOC.part1(["rrrbrr?b"]) if res != 4, do: raise "test input is #{res} but should be 4" res = AOC.part1(["rg"]) if res != 2, do: raise "test input is #{res} but should be 2" IO.puts "result: #{AOC.part1(input)}"I had that too, luckily for me I didn’t need to drbug but only paste the correct number.
What do you mean by “disassemble” the input?
By disassemble I mean that I’m not working with the input string itself but transforming it into one list of all the positions of the illegible characters and one map with all the legible ones and their position.
I think I’ll have another look and compare the results I get with with what they should be for specific codes. I tried just putting in a number about 50 higher than my result and it was still too low so I’m not just off by one.
ARM Assembly
No static allocation today! Feels more clean, can read arbitrary large inputs. Also massively helps with binary size. After stripping, it’s got only
976Bytes of size.The code is enormous of course, again. Especially because it requires a three-times nested loop. Runs immeasurably fast and has, according to
time384k maxresident memory.196 lines of assembly
.global _start // Declare the entry point of the program .align 4 // Align the next instruction to a 4-byte boundary _start: bl slurp // make space for pattern buffer sub x0, x19, x20 add x0, x0, x19 mov x8, #214 // brk svc 0 mov x23, x19 // pattern buffer mov x27, x20 bl repair bl print mov x0, x27 bl join_lines mov x20, x27 bl repair bl print b exit // x0: str join_lines: sub x0, x0, #1 mov x1, x0 // to join_lines_body: ldrb w2, [x0, #1]! cmp w2, #10 // newline b.eq join_lines_body strb w2, [x1, #1]! cbnz w2, join_lines_body mov w3, #10 // write final newline strb w3, [x1] strb wzr, [x1, #1] ret // x0: buffer, w1: byte // out x2: offset find_byte_index: mov x2, #-1 find_byte_index_again: add x2, x2, #1 ldrb w3, [x0, x2] cmp w1, w3 b.ne find_byte_index_again ret // x0: from, x1: to, x2: n copy_bytes: b copy_bytes_tail copy_bytes_body: ldrb w3, [x0], #1 strb w3, [x1], #1 sub x2, x2, #1 copy_bytes_tail: cbnz x2, copy_bytes_body ret // in: x20: barcode strings // out: x0=#instructions repair: stp x29, x30, [sp, #-16]! mov x19, #0 mov x26, #0 // counter for instructions repair_each_barcode_head: ldrb w0, [x20] cbz w0, repair_done // end of buffer repair_each_barcode_body: mov x0, x20 mov x1, #10 bl find_byte_index // x2: length of barcode mov x21, x2 repair_each_divisor_head: mov x18, #0 // iterator, divisor b repair_each_divisor_tail repair_each_divisor_body: mov x0, x20 mov x1, x23 mov x2, x18 bl copy_bytes repair_unify_head: mov x24, #-1 // iterator, barcode index mov x25, #-1 // iterator, pattern index b repair_unify_tail repair_unify_body: ldrb w0, [x20, x24] ldrb w1, [x23, x25] cmp w0, w1 b.eq repair_unify_tail // fallthrough: not equal cmp w0, #63 b.eq repair_unify_tail // '?' in barcode always matches cmp w1, #63 // '?' = 63 b.ne repair_each_divisor_tail // '?' in pattern must be copied strb w0, [x23, x25] repair_unify_tail: // increment iterator vars add x24, x24, #1 add x25, x25, #1 cmp x25, x18 csel x25, xzr, x25, eq // wrapping (modulo) cmp x24, x21 // barcode-index = barcode-length b.ne repair_unify_body // fallthrough, pattern did unify add x26, x26, x18 b repair_each_barcode_tail repair_each_divisor_tail: add x18, x18, #1 cmp x18, x21 b.le repair_each_divisor_body // fallthrough: not divisor != length repair_each_barcode_tail: add x20, x20, x21 add x20, x20, #1 // skip the newline b repair_each_barcode_head repair_done: ldp x29, x30, [sp], #16 mov x0, x26 ret // out: x19: current brk, x20: buf slurp: stp x29, x30, [sp, #-16]! mov x0, #0 mov x8, #214 // brk svc 0 mov x19, x0 // current brk mov x20, x0 // buf base slurp_again: add x0, x19, #4096 mov x8, #214 // brk svc 0 mov x19, x0 mov x0, #0 // stdin sub x1, x19, #4096 mov x2, #4096 mov x8, #0x3F // read svc 0 cbz x0, exit_fail // end of file cmp x0, #4096 b.eq slurp_again ldp x29, x30, [sp], #16 sub x1, x19, #4096 strb wzr, [x1, x0] ret print: adr x1, print_buf mov w2, #10 strb w2, [x1, #15]! mov x4, x1 mov x5, #1 print_format: udiv x1, x0, x2 smull x3, w1, w2 sub x3, x0, x3 add x3, x3, #48 strb w3, [x4, #-1]! add x5, x5, #1 mov x0, x1 cbnz x0, print_format print_write: mov x0, #1 mov x1, x4 mov x2, x5 mov x8, #64 // write svc 0 ret exit: mov x0, #0 // x0 = 0 (exit code) exit_fail: mov x8, #0x5D // x8 = 93 (sys_exit) svc 0 .section .data print_buf: .fill 16Actually, I did now try more invasive measurements methods but everything jitters so hard it’s basically useless. One run it’s 2ms, another it’s 5ms.
Maybe I should note that it uses linux syscalls and will not run anywhere else.
Hare
This one wasn’t that hard, it just took me time to fix all the bugs. A good thing tests exist.
part1
fn nb_unique_letters(line: []u8) size = { let letters: []u8 = alloc([], 0)!; defer free(letters); for (let l .. line) { if (l != '?' && !bytes::contains(letters, l)) { append(letters, l)!; }; }; return len(letters); }; @test fn nb_unique_letters() void = { assert(nb_unique_letters([]) == 0); assert(nb_unique_letters(['r', 'b', 'v']) == 3); assert(nb_unique_letters(['r', 'b', 'b']) == 2); assert(nb_unique_letters(['?', 'b', 'b']) == 1); assert(nb_unique_letters(['?', 'b', 'b', '?', '?', 'v']) == 2); }; fn check_column(line: []u8, mod: size, col: size) bool = { const length = len(line); let max_row = length / mod; let letter: u8 = '?'; for (let row = 0z; row <= max_row; row += 1) { const idx = row * mod + col; if (idx >= length) break; const l = line[idx]; if (letter == '?') { letter = l; } else if (l != '?' && letter != l) { return false; }; }; return true; }; @test fn check_column_simple() void = { let line: []u8 = ['r', '?']; assert(check_column(line, 1, 0)); }; fn mininsn(line: []u8) int = { const length = len(line); let min = nb_unique_letters(line); if (min == 0) return 1; for (min <= length) { let checked = true; for (let col = 0z; col < min; col += 1) { checked = checked && check_column(line, min, col); if (!checked) break; }; if (checked) return min: int; min += 1; }; return 0; }; @test fn min_o__v___y() void = { const line = "o??v???y"; const min = mininsn(strings::toutf8(line)); const errmsg = fmt::asprintf("{} != {}", min, 5)!; defer free(errmsg); assert(min == 5, errmsg); }; fn part1(scan: *bufio::scanner) (int | aoc::error) = { let sum = 0; for (true) { match (bufio::read_line(scan)!) { case io::EOF => break; case let line: []u8 => { sum += mininsn(line); }; }; }; return sum; };part 2
fn part2(scan: *bufio::scanner) (int | aoc::error) = { let barcode: []u8 = alloc([], 0)!; defer free(barcode); for (true) { match (bufio::read_line(scan)!) { case io::EOF => break; case let line: []u8 => { append(barcode, line...)!; }; }; }; return mininsn(barcode); };C
Was set on the final solution quite quickly: for every stride and offset, find the first non-? character, then check the remaining characters against it. My only trouble was fumbling some of the loop exits and such. The solution worked well for part 2, I just had to make it read the full input into a buffer.
Code
#include <stdio.h> static int solve(const char *word, int len) { int stride, off, i,j; for (stride=1; stride<len; stride++) { for (off=0; off<stride; off++) { for (i=off; i<len && word[i] == '?'; i+=stride) ; for (j=i+stride; j<len; j+=stride) if (word[j] != '?' && word[j] != word[i]) goto next; } break; /* match */ next: } return stride; } int main() { static char buf[5*4096]; int p1=0, cur=0, len; while (fgets(buf+cur, sizeof(buf)-cur, stdin)) { for (len=0; buf[cur+len] && buf[cur+len]!='\n'; len++) ; p1 += solve(buf+cur, len); cur += len; } printf("04: %d %d\n", p1, solve(buf, cur)); }Bench still looking good:
day01 0:00.00 1500 Kb 0+83 faults day02 0:00.00 1504 Kb 0+84 faults day03 0:00.00 1572 Kb 0+88 faults day04 0:00.00 1648 Kb 0+90 faultsRust
I start checking cycles with increasing length, each time going through the string and replacing ‘?’ in the cycle with the required colors until a conflict pops up. If the end of the string is reached, I have found the shortest instruction sequence. Part 1 takes 975µs, Part 2 takes 2.7ms.
fn min_instructions(code: &str) -> usize { 'next_length: for n in 1..code.len() { let mut instructs = vec![b'?'; n]; for (i, required) in code.as_bytes().iter().enumerate() { if *required != b'?' { if instructs[i % n] == b'?' { instructs[i % n] = *required; } else if instructs[i % n] != *required { continue 'next_length; } } } return n; } code.len() } fn part1(input: String) { let sum = input.lines().map(min_instructions).sum::<usize>(); println!("{sum}"); } fn part2(mut input: String) { input.retain(|c| c != '\n'); println!("{}", min_instructions(&input)); } util::aoc_main!();Basically the same solution, just with some slight stylistic differences (using
(1..).find()instead of a for loop, taking a mutable reference instead of writing[]three times). Was expecting to need some crazy optimization for part 2. Ran my algorithm from part 1 unaltered, just to see how it would perform. And then the answer popped out immediately, without even needing to pass the--releaseflag…Cool thing about my part 2 result
It was 1729, a very nice number!
Rust
spoiler
fn check_string(s: &str, len: usize, offset: usize) -> bool { let mut char = "?"; let mut i = offset; while let Some(c) = s.get(i..i+1) { if char == "?" { char = c; } if c != "?" && c != char { return false } i+=len } true } fn get_min_moves(s: &str) -> usize { 'outer: for len in 1..s.len() { for offset in 0..len { if !check_string(s, len, offset) { continue 'outer } } return len } s.len() } #[test] fn test_y2026_day4_part1() { let input = include_str!("../../input/2026/day_4.txt"); let total: usize = input.lines().map(|l| { get_min_moves(l) }).sum(); println!("{total}") } #[test] fn test_y2026_day4_part2() { let input = include_str!("../../input/2026/day_4.txt"); let mut string: String = String::with_capacity(input.len()); input.lines().for_each(|l| { string += l; }); let total = get_min_moves(&string); println!("{total}") }Bit disappointing that the approach for pt1 works completely out of the box for pt2. Not terribly interesting. Might have a crack at an excel solution still. edit: CBF with excel, someone else can give it a go.
Yeah. Your mission, should you choose to accept it, is to suggest an algorithm that would work for part 1, but would fail for part 2 so you’d have to rewrite it.
I suggest generating all the possible repeat sequences, and then testing them all to see whether they’d match the barcode. The longest ‘part 1’ barcode I have is 8 characters; given 6 colours, there’s 8 * 6 = 48 strings to test if there’s a single repeat match, (8/2) * 6^2 = 144 double repeat matches, (8/3) * 6^3 = 432 trebles, …, (8/8) * (6^8) = 1679616 eight character repeats. That shouldn’t take a ridiculous amount of time. Probably have to generate them on demand, as otherwise you’d need to spend a lot of £££ on RAM to hold them all, but I’m thinking you’d churn through them in a few minutes.
My part 2 answer is 1000+, so testing the 6^1000 ~= 10^778 possibilities to see if any of them work would take too damn long. Although you never know, might get lucky if you just do them at random.
I do wonder if that was the intent, that people would brute force the instructions, and then need to do something more in line with what we all did for pt2? Maybe we’ve been doing this too long and we aren’t doing the dumb first solutions anymore :|
Probably yes, I can imagine past me brute-forcing the printer patterns
deleted by creator
Kotlin
Now that I read the thread, it seems everyone here saw the needed logic quite quickly. I actually started with a brute force approach which solved part 1 decently fast, but for part 2 it couldn’t even crack the example, even with parallelization (those attempts are in my commit history if you’re curious).
After reapproaching step 2, I realized the problem is actually quite simple, I believe my solution is identical to most ones here.One annoying thing, my
fit()function is very un-Kotlin-like. If anyone has some cool ideas how to give it more of a Kotlin feel, do let me know because I can’t think of anything.Solution
class Day04 : Puzzle { private lateinit var barcodes: List<String> override fun readFile() { val input = readInputFromFile(2026, 4, false) barcodes = input.lines().filter { it.isNotBlank() } } override fun solvePartOne(): String { return barcodes.sumOf { getShortestFit(it) }.toString() } override fun solvePartTwo(): String { return getShortestFit(barcodes.joinToString("")).toString() } private fun getShortestFit(barcode: String): Int { return barcode.indices.asSequence() .map { barcode.substring(0, it + 1) } .first { fit(barcode, it.toMutableList()) } .length } private fun fit(barcode: String, test: MutableList<Char>): Boolean { val offset = test.size var i = offset while (i < barcode.length) { for (j in test.indices) { if (i + j >= barcode.length) return true val bChar = barcode[i + j] val tChar = test[j] when { bChar == tChar || bChar == '?' -> continue tChar != '?' -> return false tChar == '?' -> test[j] = bChar else -> throw IllegalStateException("Encountered unknown characters: barcode='$bChar', test='$tChar'") } } i += offset } return true } }full code on Codeberg
Uiua
Brute force was fast enough. It just wraps the array around a scytale of increasing diameter until all given values in each row match.
Fit ← /×≤1≡(⧻◴▽⊸≠@?)⍉⬚@?↯⊂∞ Min ← ⊙◌⍢(+1|¬Fit)1 "rgbrgbrgbr\n?rv\no??v???y\n??bg?v??\n??b?????\n???" ⊃(/+≡◇Min ⊜□|Min▽)⊸≠@\nRust
Same basic algorithm as @addie@feddit.uk’s C++ solution, probably the same off-by-one during development too. Use the input
orbif you pass the tests of part 1, but not the real input. The output should help you find the problem in your code. (I only found it after reading addie’s part 1 solution.)Its testing each prefix of the barcode, starting with the smallest and stopping as soon as it found a match. During matching,
?symbols in the pattern are replaced with the characters from the barcode, and modulo is used to repeat the pattern. My implementation doesn’t copy chars as often as addie’s, but that shouldn’t make much of a difference during runtime.Code
use std::fs; fn main() { run(&fs::read_to_string("../../inputs/2026/4") .expect("Could not read input file")); // println!("expected p1: {}", 3); // run("orb"); } fn run(contents: &str) { let mut sum = 0; for liner in contents.lines() { sum += fun_name(liner); } println!("p1: {}", sum); let c = contents.replace('\n', ""); println!("p2: {}", fun_name(&c)); } fn fun_name(liner: &str) -> usize { let line: Vec<_> = liner.chars().collect(); for l in 1..=line.len() { if check(&line[0..l], &line) { return l; } } panic!(); } fn check(pattern: &[char], line: &Vec<char>) -> bool { let mut p = Vec::with_capacity(pattern.len()); p.extend_from_slice(pattern); let plen = p.len(); for i in 0..line.len() { if p[i%plen] == line[i] { continue; } if p[i%plen] == '?' { p[i%plen] = line[i]; continue; } if line[i] == '?' { continue; } // now both the pattern and the line are different and contain no ? at this pos return false; } // viz // let mut l1 = "#".to_owned(); // let mut l2 = " ".to_owned(); // for i in 0..line.len() { // if i > 0 && i%plen == 0{ // l1.push('|'); // l2.push('|'); // } // l1.push(p[i%plen]); // l2.push(line[i]); // } // println!("{}\n{}", l1, l2); true }Rust
fn parts(input: &str) -> (String, String) { let match_chars = |a: u8, b: u8| Some(a.max(b)).filter(|_| a.min(b) == b'?' || a == b); let solve_barcode = |line: &str| { (1..=line.len()) .filter(|len| { (0..*len).all(|offset| { line.bytes() .skip(offset) .step_by(*len) .try_fold(b'?', match_chars) .is_some() }) }) .next() .unwrap() }; let part1 = input.lines().map(|line| solve_barcode(line)).sum::<usize>(); let part2 = solve_barcode(&input.replace("\n", "")); (part1.to_string(), part2.to_string()) }Rust
use itertools::Itertools; fn min_instructions(barcode: &[Option<usize>]) -> usize { let mut fail; for i in 1..barcode.iter().len() { fail = false; for j in 0..i { if barcode[j..].iter().step_by(i).flatten().unique().count() > 1 { fail = true; break; } } if !fail { return i; } } barcode.iter().len() } pub fn solve(text: String) -> (usize, usize) { let barcodes = text.trim().lines().map(|s| { s.chars() .map(|c| "_roygbv".find(c)) .collect::<Vec<Option<usize>>>() }); let part1 = barcodes.clone().map(|b| min_instructions(&b)).sum(); let part2 = min_instructions(&barcodes.flatten().collect::<Vec<_>>()); (part1, part2) }TXR
(defun day04 () (let ((lines (file-get-lines "04-input"))) (flet ((pt1 () (sum-each ((line lines)) (shortest-cycle line))) (pt2 () (shortest-cycle [apply append lines]))) (put-line `1: @(pt1)`) (put-line `2: @(pt2)`)))) (defun unify (str1 str2) (and str1 str2 (map (lambda (c1 c2) (cond ((eq c1 c2) c1) ((eq c1 #\?) c2) ((eq c2 #\?) c1) (t (return-from unify nil)))) str1 str2))) (defun shortest-cycle (str) (each ((stride 1..(succ (len str)))) (when [reduce-left unify (tuples stride str)] (return stride))))








