diff options
-rw-r--r-- | AoC2022/13/solver.lisp | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/AoC2022/13/solver.lisp b/AoC2022/13/solver.lisp new file mode 100644 index 0000000..62b8c2d --- /dev/null +++ b/AoC2022/13/solver.lisp @@ -0,0 +1,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) |