..

Advent 2026 Day 1

And so we begin! I’m doing these in Guile, because I like lispy languages, but it’s also nice to be more familiar when I’m writing system stuff for Guix.

Part 1

You’re given a list of container ID numbers as the puzzle input. The problem asks you to identify the three most common IDs in the list and output their product. I started with a helper module to read an input file to a list of lines, preserving empty lines (which are often semantically important).

(define-module (aoc input)
  #:use-module (ice-9 rdelim)
  #:export (read-lines))

(define (read-lines port)
  (let loop ((lines '()))
    (let ((line (read-line port)))
      (if (eof-object? line)
          (reverse lines)
          (loop (cons line lines))))))

Just as a warm-up, I’m not doing anything algorithmically difficult here. The strategy is to mantain an association list (a list of cons-pairs) of (id . count). In essence it’s a more expensive alternative to a hash table. This is O(n^2) for insertion, and O(nlogn) for sorting. Start with some boilerplate to get our input.

(use-modules (aoc input)
             (srfi srfi-1))

(define input
  (call-with-input-file "../input/day1" read-lines))

Now we can produce the full list of counts per ID.

(define (frequency input)
  "Return (id . count) pairs, sorted decreasing by count."

  (let loop ((rest input) (counts '()))
    (if (null? rest)
        (sort counts (lambda (a b) (> (cdr a) (cdr b))))
        (let* ((cur (string->number (first rest)))
               (count (or (assoc-ref counts cur) 0)))
          (loop (cdr rest)
                (assoc-set! counts cur (+ count 1)))))))

Output is just the product of the top three elements of this list.

(define (part1 input)
  (apply * (map car (take (frequency input) 3))))

Part 2

This is a very simple corollary to part 1: find the product of the three least common IDs in the list. We’re all set up with frequency, we just need the last three elements of the list.

(define (part2 input)
  (apply * (map car (take-right (frequency input) 3))))

Improvements

As disclaimed above, this is most certainly an inefficient algorithm. I think we could turn this into an O(n) solution with the observation that the IDs are all three digits.

  1. create a zeroed array of 1000 elements
  2. maintain an initially empty list of the most common IDs
  3. process the list, incrementing the count per element
  4. as a second pass, process all the non-zero entries, maintaining a top-3 of most or least common IDs