• Home
  • ·
  • Artwork
  • ·
  • Notes
  • ·
  • Projects
  • Watercolor and chalk landscape of the Bohemian Forest (Böhmerwald) by Anton Emanuel Peschka, 1931

    Böhmerwald (1931) by Anton Emanuel Peschka. Public domain.

    Day 2: Fulminating Farmland

    Dec 2, 2026

    (use-modules (ice-9 rdelim)
                 (srfi srfi-1)   ; take drop
                 (srfi srfi-11)) ; let-values
    
    ;; Read input
    
    (define (read-file path)
      (call-with-input-file path
        (lambda (port)
          (string-trim-right (read-line port)))))
    
    ;; Part 1
    
    (define (to-val c)
      (case c
        ((#\r) 0)
        ((#\o) 1)
        ((#\y) 2)
        ((#\g) 3)
        ((#\b) 4)
        (else 5)))
    
    (define (ab-dist a b)
      (if (< a b)
          (- b a)
          (+ 6 (- b a))))
    
    (define (calc-dist items)
      (map ab-dist (cons 0 items) items))
    
    ;; Part 2
    
    (define* (get-max-idx items
                          #:optional (idx 0) (best 0) (maxv 0))
      (if (null? items)
          (values best maxv)
          (let ((x (car items)))
            (cond
             ((= x 6)    (values idx x))
             ((> x maxv) (get-max-idx (cdr items) (1+ idx) idx x))
             (else       (get-max-idx (cdr items) (1+ idx) best maxv))))))
    
    (define (remove-idx lst idx)
      (append (take lst idx)
              (drop lst (1+ idx))))
    
    (define (calc-dist-part2 pos items)
      (map (lambda (item) (ab-dist pos item)) items))
    
    (define (longest-dist items)
      (let loop ((remaining items)
                 (curr 0)
                 (acc 0))
        (if (null? remaining)
            acc
            (let ((dists (map (lambda (x) (ab-dist curr x)) remaining)))
              (let-values (((idx max-dist) (get-max-idx dists)))
                (loop (remove-idx remaining idx)
                      (list-ref remaining idx)
                      (+ acc max-dist)))))))
    
    ;; Results
    
    (define input (map to-val (string->list (read-file "input.txt"))))
    
    (format #t "Part 1: ~a~%" (apply + (calc-dist input)))
    (format #t "Part 2: ~a~%" (longest-dist input))