commit 3485ab4d7bc8df427f64ce0fdf79a9cdb55bccf5 parent abba33e8d2bac06e0a3f5057c7e164b078c2b7bb Author: Lukas Henkel <lh@entf.net> Date: Mon, 11 Dec 2023 18:59:41 +0100 Refactor day 11 Diffstat:
M | src/day-11.lisp | | | 47 | ++++++++++++++++++++++++----------------------- |
1 file changed, 24 insertions(+), 23 deletions(-)
diff --git a/src/day-11.lisp b/src/day-11.lisp @@ -3,8 +3,7 @@ (:export #:day-11)) (in-package #:aoc/day-11) -(defun find-galaxies (map &optional (expansion-factor 2)) - (decf expansion-factor) +(defun find-galaxies (map) (let (galaxies empty-rows empty-cols) @@ -20,26 +19,28 @@ unless (loop for x from 0 below (input-map-width map) thereis (char= (map-cell map (cons x y)) #\#)) do (push y empty-rows)) - (loop for galaxy in galaxies - collect (cons (+ (point-x galaxy) - (* (count-if (curry #'> (point-x galaxy)) empty-cols) - expansion-factor)) - (+ (point-y galaxy) - (* (count-if (curry #'> (point-y galaxy)) empty-rows) - expansion-factor)))))) + (values galaxies empty-rows empty-cols))) + +(defun expand-universe (galaxies empty-rows empty-cols expansion-factor) + (decf expansion-factor) + (loop for galaxy in galaxies + collect (cons (+ (point-x galaxy) + (* (count-if (curry #'> (point-x galaxy)) empty-cols) + expansion-factor)) + (+ (point-y galaxy) + (* (count-if (curry #'> (point-y galaxy)) empty-rows) + expansion-factor))))) + +(defun sum-distances (galaxies) + (loop for (galaxy-1 . rest) on galaxies + while rest + sum (loop for galaxy-2 in rest + sum (manhattan-distance galaxy-1 galaxy-2)))) (defun day-11 (input) - (let* ((map (make-map input)) - (galaxies-1 (find-galaxies map)) - (galaxies-2 (find-galaxies map 1000000)) - (task-1 0) - (task-2 0)) - (map-combinations (lambda (p) - (incf task-1 (apply #'manhattan-distance p))) - galaxies-1 - :length 2) - (map-combinations (lambda (p) - (incf task-2 (apply #'manhattan-distance p))) - galaxies-2 - :length 2) - (values task-1 task-2))) + (multiple-value-bind (galaxies empty-rows empty-cols) + (find-galaxies (make-map input)) + (let ((galaxies-1 (expand-universe galaxies empty-rows empty-cols 2)) + (galaxies-2 (expand-universe galaxies empty-rows empty-cols 1000000))) + (values (sum-distances galaxies-1) + (sum-distances galaxies-2)))))