Advent of Code '23 - day 15

Table of Contents

Part one was pretty simple, and only had a very little influence over part two. I feel like my list skills are improving.

Input

Example

rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7

Part 1

  • Determine the ASCII code for the current character of the string.
  • Increase the current value by the ASCII code you just determined.
  • Set the current value to itself multiplied by 17.
  • Set the current value to the remainder of dividing itself by 256.
(apply '+ (mapcar (lambda (s)
                  (seq-reduce (lambda (v m) (% (* 17 (+ v m)) 256)) s 0))
                (string-split input "," t)))

Part 2

(defun aoc23/seq-to-cons (seq)
  (let ((label "")
        (lens 0))
    (seq-do (lambda (v)
              (cond ((= v ?-)
                     (setq lens ?-))

                    ((= v ?=)
                     (setq lens ?=))

                    ((= lens ?=)
                     (setq lens (- v ?0)))

                    (t (setq label (concat label (list v))))))
            seq)
    (cons label lens)))

(defun aoc23/hash (label)
  (seq-reduce (lambda (v m) (% (* 17 (+ v m)) 256)) label 0))

(defun aoc23/process-lens (lenses lens)
  (cond ((eq (cdr lens) ?-)
         (aoc23/--remove-lens lenses lens))
        (t
         (aoc23/--replace-lens lenses lens))))

(defun aoc23/--replace-lens (lenses lens)
  (if (assoc (car lens) lenses)
      (mapcar (lambda (l)
                       (if (string= (car l) (car lens))
                           lens
                         l)) lenses)
    (append lenses (list lens))))


(defun aoc23/--remove-lens (lenses lens)
  (seq-filter (lambda (l) (not (string= (car l) (car lens)))) lenses))

(defun aoc23/part-2 (input)
  (let ((map (make-hash-table))
        (ret 0))
    (seq-do (lambda (c)
              (let* ((label (car c))
                     (lens (cdr c))
                     (box (aoc23/hash (car c)))
                     (lenses (gethash box map)))
                (puthash box (aoc23/process-lens lenses c) map))

              )
            (mapcar 'aoc23/seq-to-cons
                    (string-split input "," t)))
    (maphash (lambda (box value)
               (seq-do-indexed (lambda (lens i)
                                 (setq ret (+ ret
                                              (* (1+ box)
                                                 (1+ i)
                                                 (cdr lens)))))
                               value))
             map)
    ret))

(aoc23/part-2 input)