Advent 2026 Day 4
A bit of an algorithmic teaser for Friday.
Part 1
You are given a list of barcodes, containing the colours roygbv or
? indicating an illegible colour. For each line of the input,
determine the shortest repeating string of colours that will cover the
barcode, treating the illegible ? as a wildcard. For example,
rgbrgbrgbr can be covered by the length 3 string rgb. Or
??bg?v?? can be covered by, for example, bvbg.
Any kind of brute force attempt is going to be very expensive (not to
mention unsatisfying as a solution). An important point is that you
don’t actually have to construct the solution: you can just figure out
its shortest length. To determine whether a solution of length n
exists for the string s, construct a list containing n sets,
indexed i = 0..n-1. Each set contains every colour within s[i + m*n]. If the set is empty at a given index, we only encountered
illegible entries, so we’re free to choose the solution at that
index. Similarly, a set with a single entry means that colour is in
the solution at that index. However, if a set has cardinality greater
than one, no solution is possible: we’d have to have two colours in
the same place in the solution!
I think this is fairly easy to understand, and lends itself to a clear
implementation. We use bitvector for the set, since we know there
are only 6 posible positions. A helper function translates colours to
these positions. We can then create the bit vectors for a given string,
candidate solution length, and index within the solution.
(use-modules (aoc input)
(aoc util)
(ice-9 hash-table)
(srfi srfi-1))
(define colours
(alist->hash-table
(map cons (string->list "roygbv") (iota 6))))
(define (seen-colours line n i)
"Get a bitvector of colours seen at position I of a length N instruction string
for vector LINE."
(let ((bv (make-bitvector 6 #f)))
(let loop ((pos i))
(if (>= pos (vector-length line))
bv
(let ((c (vector-ref line pos)))
(unless (char=? c #\?)
(bitvector-set-bit! bv (hash-ref colours (vector-ref line pos))))
(loop (+ pos n)))))))
The actual solution falls out fairly elegantly: find the smallest candidate solution length such that every bit vector has cardinality 0 or 1. Then, just sum that over all lines of the input.
(define (minimum-instruction-count line)
"Find the smallest instruction set for string LINE."
(let ((line (list->vector (string->list line))))
(find
(lambda (n)
(every
(lambda (i)
(let ((bv (seen-colours line n i)))
(<= (bitvector-count bv) 1)))
(iota n)))
(iota (vector-length line) 1))))
(define (part1 input)
(sum-over minimum-instruction-count input))
Part 2
I figured this was coming, and it catches out the brute force solution. Instead of taking the input as a series of lines, concatenate all of the lines together. We end up with a much longer string, but the algorithm I’ve implemented doesn’t scale badly here.
(define (part2 input)
(minimum-instruction-count (string-join input "")))