Day 7: Laboratories

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
    2
    ·
    3 days ago

    My choice of representation for part 1 ended up being fortunate, as all I needed to change for part 2 was three setf in propagate that became incf. This was also another good use case for multiple return values, as it’s the beam vector you want to reduce on, but for part 1 the split count needs to come along for the ride.

    (defun parse-line (line)
      (let ((result (make-array (length line) :initial-element 0)))
        (loop for i from 0 to (1- (length line))
              if (member (char line i) '(#\^ #\S))
                do (setf (aref result i) 1))
        result))
    
    (defun read-inputs (filename)
      (let ((input-lines (uiop:read-file-lines filename)))
        (mapcar #'parse-line input-lines)))
    
    (defun propagate (in-beams splitters)
      (let ((out-beams (make-array (length in-beams) :initial-element 0))
            (splits 0))
        (loop for i from 0 to (1- (length in-beams))
              if (not (zerop (aref in-beams i)))
                do (if (not (zerop (aref splitters i)))
                       (progn (incf (aref out-beams (1- i)) (aref in-beams i))
                              (incf (aref out-beams (1+ i)) (aref in-beams i))
                              (incf splits))
                       (incf (aref out-beams i) (aref in-beams i))))
        (values out-beams splits)))
    
    (defun propagate-all (initial-beam-vector splitter-map)
      (let* ((total-splits 0)
             (final-beam-vector
               (reduce #'(lambda (in-beams splitters)
                           (multiple-value-bind (out-beams this-splits)
                               (propagate in-beams splitters)
                             (incf total-splits this-splits)
                             out-beams))
                       splitter-map :initial-value initial-beam-vector)))
        (values final-beam-vector total-splits)))
    
    (defun main-1 (filename)
      (let ((grid (read-inputs filename)))
        (multiple-value-bind (final-beam-vector total-splits)
            (propagate-all (car grid) (cdr grid))
          total-splits)))
    
    (defun main-2 (filename)
      (let ((grid (read-inputs filename)))
        (multiple-value-bind (final-beam-vector total-splits)
            (propagate-all (car grid) (cdr grid))
          (reduce #'+ (coerce final-beam-vector 'list)))))