aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/13/solver.lisp
blob: 62b8c2d2006ddcaa7aed171a5cbb11c297693d83 (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
37
38
39
40
41
42
(ql:quickload '(fiveam cl-json))

(defun input (filename &optional dividers)
  (with-open-file (in filename)
    (let ((data (loop for a = (ignore-errors (list (json:decode-json in) (json:decode-json in)))
                  while a
                  nconc a)))
      (if dividers (append '(((2)) ((6))) data) data))))

(defun compare (f s)
  (cond
    ((eq f s) 'next)
    ((and      (null f)  (not (null s))) t)
    ((and (not (null f))      (null s))  nil)
    ((and (integerp f) (integerp s)) (< f s))
    ((and (integerp f)    (consp s)) (compare (list f) s))
    ((and    (consp f) (integerp s)) (compare f (list s)))
    ((let ((result (compare (car f) (car s))))
       (if (eq 'next result) (compare (cdr f) (cdr s))
           result)))))

(defun solver-1 (filename)
  (loop for i from 1
        for (a b) on (input filename) by #'cddr
        when (compare a b)
          sum i))

(fiveam:test first
  (fiveam:is (= 13 (solver-1 "eg-in")))
  (fiveam:is (= 5330 (solver-1 "input"))))

(defun solver-2 (filename)
  (let ((packages (sort (input filename t) #'compare)))
    (*
     (1+ (position '((2)) packages :test #'equal))
     (1+ (position '((6)) packages :test #'equal)))))

(fiveam:test second
  (fiveam:is (= 140 (solver-2 "eg-in")))
  (fiveam:is (= 27648 (solver-2 "input"))))

(fiveam:run-all-tests)