commit 1fa917d31e78f7342ab690a3447ef3ac47c9fcd9 parent eba1e3d671fb248cdf9966ced55805a490815e97 Author: Lukas Henkel <lh@entf.net> Date: Thu, 5 Dec 2024 07:06:24 +0100 Simplify Diffstat:
M | src/day-5.lisp | | | 37 | +++++++++++-------------------------- |
1 file changed, 11 insertions(+), 26 deletions(-)
diff --git a/src/day-5.lisp b/src/day-5.lisp @@ -8,31 +8,18 @@ (uiop:split-string line :separator '(#\|)))) (defun parse-update (line) - (map 'vector - #'parse-integer - (uiop:split-string line :separator '(#\,)))) - -(defun update-ordered-p (update rules) - (loop for (first second) in rules - for pos-first = (position first update) - for pos-second = (position second update) - unless (or - (null pos-first) - (null pos-second) - (< pos-first pos-second)) - do (return nil) - finally (return t))) + (mapcar #'parse-integer + (uiop:split-string line :separator '(#\,)))) (defun order-update (update rule-map) (sort update (lambda (first second) (not (gethash (list second first) rule-map))))) (defun middle-page-number (update) - (aref update (floor (length update) 2))) + (nth (floor (length update) 2) update)) (defun day-5 (input) - (loop with rules = nil - with rule-map = (make-hash-table :test #'equal) + (loop with rule-map = (make-hash-table :test #'equal) with processing-updates = nil with task-1 = 0 with task-2 = 0 @@ -40,15 +27,13 @@ until (null line) do (cond (processing-updates - (let ((update (parse-update line))) - (if (update-ordered-p update rules) - (incf task-1 (middle-page-number update)) - (progn - (setf update (order-update update rule-map)) - (incf task-2 (middle-page-number update)))))) + (let* ((update (parse-update line)) + (sorted (order-update (copy-seq update) rule-map)) + (middle (middle-page-number sorted))) + (if (seq= update sorted) + (incf task-1 middle) + (incf task-2 middle)))) ((string= line "") (setf processing-updates t)) - (t (let ((rule (parse-rule line))) - (setf (gethash rule rule-map) t) - (push rule rules)))) + (t (setf (gethash (parse-rule line) rule-map) t))) finally (return (values task-1 task-2))))