commit 35c946e7d5e16c208c621d362897e660a52d3ff0 parent b68ab874ab6ed68a7b9d5b4914feeeed7603850f Author: Lukas Henkel <lh@entf.net> Date: Sun, 1 Dec 2024 12:36:26 +0100 Optimize task 2 Diffstat:
M | src/day-1.lisp | | | 19 | +++++++++++++------ |
1 file changed, 13 insertions(+), 6 deletions(-)
diff --git a/src/day-1.lisp b/src/day-1.lisp @@ -4,16 +4,23 @@ (in-package #:aoc/day-1) (defun day-1 (input) - (let* ((numbers (mapcar #'read-number-list (read-input input))) - (left (mapcar #'car numbers)) - (right (mapcar #'cadr numbers)) - (left (sort left #'<)) - (right (sort right #'<))) + (let ((right-counts (make-hash-table)) + left + right) + (loop with input = (mapcar #'read-number-list (read-input input)) + for row in input + for right-num = (cadr row) + do (push (car row) left) + (push right-num right) + (ensure-gethash right-num right-counts 0) + (incf (gethash right-num right-counts)) + finally (setf left (sort left #'<) + right (sort right #'<))) (values (loop for number-left in left for number-right in right for distance = (abs (- number-left number-right)) sum distance) (loop for number-left in left - for number-of-instances = (count number-left right) + for number-of-instances = (or (gethash number-left right-counts) 0) sum (* number-left number-of-instances)))))