summary refs log tree commit diff
path: root/2024/d01.lisp
blob: b4ec6f229761af5efd86a3505d1cfc0d9749f2d7 (plain)
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
(in-package :aoc/2024)

(defparameter *input/d1*
              (asdf:system-relative-pathname :advent "2024/d01.input"))

(defun readlists (filename)
  "Read the left and right columns of numbers into individual lists"
  (let ((left-numbers '())
        (right-numbers '()))
    (with-open-file (stream filename :direction :input)
      (loop for line = (read-line stream nil nil)
            while line do
              (let* ((tab-pos (search "   " line))
                     (left (parse-integer (subseq line 0 tab-pos)))
                     (right (parse-integer (subseq line (1+ tab-pos)))))
                (push left left-numbers)
                (push right right-numbers))))
    (list
     (nreverse left-numbers)
     (nreverse right-numbers))))

(let* ((input-list (readlists *input/d1*))
       (left (sort (first input-list) #'<))
       (right (sort (second input-list) #'<))
       (diff (mapcar #'- left right))
       (absdiff (mapcar #'abs diff))
       (result (apply #'+ absdiff)))
  (print result))
; 2066446

(let* ((input-list (readlists *input/d1*))
       (left (first input-list))
       (right (second input-list))
       (result (apply #'+ (mapcar #'(lambda (x) (* x (count x right))) left))))
  (print result))
; 24931009