From 8cc2675f22d1fe94f09ad847e41a99a2450c1856 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Tue, 13 Dec 2022 15:00:12 +0100 Subject: [AoC2022] Lisp --- AoC2022/13/solver.lisp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 AoC2022/13/solver.lisp (limited to 'AoC2022/13') 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) -- cgit v1.2.3