aboutsummaryrefslogtreecommitdiff
path: root/2024/09/puzzle-1.el
blob: 5ac1a3864d5ca594b684dae06c76509d20aa47d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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"))