Day 3: Lobby

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

  • ystael@beehaw.org
    link
    fedilink
    arrow-up
    1
    ·
    3 days ago

    This problem was quite straightforward; I think it probably could have been day 1. The only interesting thing here is the use of values and multiple-value-bind, which are the standard way in Common Lisp to give a function a primary return value but also one or more advisory return values. This lets you return a rich data structure for consumers who want it, but consumers who don’t want it don’t need to parse that entire data structure to get the primary return value.

    (defun parse-line (line)
      (let ((digits (loop for i from 0 to (1- (length line))
                          collect (parse-integer line :start i :end (1+ i)))))
        (make-array (list (length digits)) :initial-contents digits)))
    
    (defun read-inputs (filename)
      (let* ((input-lines (uiop:read-file-lines filename)))
        (mapcar #'parse-line input-lines)))
    
    (defun arg-max (v &key start end)
      "Yield the index and the greatest element of vector v, between indices start (inclusive) and
      end (exclusive) if they are supplied. Returns the earliest instance of the maximum."
      (let* ((start (max 0 (or start 0)))
             (end (min (length v) (or end (length v))))
             (arg-max start)
             (val-max (aref v start)))
        (loop for i from start to (1- end)
              if (> (aref v i) val-max)
                do (progn (setf arg-max i)
                          (setf val-max (aref v i)))
              finally (return (values arg-max val-max)))))
    
    (defun bank-max-joltage (digits bank)
      (let ((search-start 0)
            (result 0))
        (loop for d from 0 to (1- digits)
              do (multiple-value-bind (digit-pos digit)
                     (arg-max bank :start search-start :end (+ (length bank) (- digits) (1+ d)))
                   (setf search-start (1+ digit-pos))
                   (setf result (+ (* 10 result) digit))))
        result))
    
    (defun main-1 (filename)
      (reduce #'+ (mapcar #'(lambda (bank) (bank-max-joltage 2 bank))
                          (read-inputs filename))))
    
    (defun main-2 (filename)
      (reduce #'+ (mapcar #'(lambda (bank) (bank-max-joltage 12 bank))
                          (read-inputs filename))))