From 58e1ec51424dbd4698727fb4b0b504a24ac7cc40 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Mon, 9 Dec 2024 14:42:49 +0100 Subject: Add 2024 day 9 part 1 --- 2024/09/puzzle-1.el | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 2024/09/puzzle-1.el (limited to '2024/09/puzzle-1.el') diff --git a/2024/09/puzzle-1.el b/2024/09/puzzle-1.el new file mode 100644 index 0000000..5ac1a38 --- /dev/null +++ b/2024/09/puzzle-1.el @@ -0,0 +1,49 @@ +(defsubst char-to-number (char) + (declare (pure t) (side-effect-free t)) + (- char ?0)) + +(defun first-nil (vector start) + (cl-loop for i from (1+ start) below (length vector) + when (null (aref vector i)) + return i + finally return (length vector))) + +(defun last-number (vector start) + (cl-loop for i from (1- start) downto 0 + when (aref vector i) + return i + finally return 0)) + +(defun solve (input-file) + (let* ((input (with-temp-buffer + (insert-file-contents-literally input-file) + (buffer-string))) + (nums (mapcar #'char-to-number input)) + (vector (make-vector (apply #'+ nums) nil)) + (i 0) (j 0)) + + ;; Populate ‘vector’ + (dolist (num nums) + (when (cl-evenp i) + (dotimes (k num) + (aset vector (+ j k) (/ i 2)))) + (cl-incf i) + (cl-incf j num)) + + ;; Swap elements + (setq i (first-nil vector 0) + j (last-number vector (length vector))) + (while (< i j) + (let ((x (aref vector i)) + (y (aref vector j))) + (aset vector i y) + (aset vector j x)) + (setq i (first-nil vector i)) + (setq j (last-number vector j))) + + ;; Compute checksum + (cl-loop for i from 0 below (length vector) + for x = (aref vector i) + while x sum (* i x)))) + +(message "%d" (solve "input")) \ No newline at end of file -- cgit v1.2.3