aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/25/solver.lisp
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2023-01-24 20:53:38 +0100
committerOscar Najera <hi@oscarnajera.com>2023-01-24 20:53:38 +0100
commitf23650fbae588817c22505f0efe91fed9bd4bc11 (patch)
tree5503cfa61767d82f3eff311913427bf985a393a5 /AoC2022/25/solver.lisp
parent10292271a2a46f13849f7e1e2a27c33e2384b2de (diff)
downloadscratch-f23650fbae588817c22505f0efe91fed9bd4bc11.tar.gz
scratch-f23650fbae588817c22505f0efe91fed9bd4bc11.tar.bz2
scratch-f23650fbae588817c22505f0efe91fed9bd4bc11.zip
Complete Advent of code day 25 lisp
Diffstat (limited to 'AoC2022/25/solver.lisp')
-rw-r--r--AoC2022/25/solver.lisp37
1 files changed, 37 insertions, 0 deletions
diff --git a/AoC2022/25/solver.lisp b/AoC2022/25/solver.lisp
new file mode 100644
index 0000000..630cd03
--- /dev/null
+++ b/AoC2022/25/solver.lisp
@@ -0,0 +1,37 @@
+(ql:quickload '(fiveam uiop))
+
+(defun encode-char (c)
+ (ecase c
+ (2 #\2)
+ (1 #\1)
+ (0 #\0)
+ (-1 #\-)
+ (-2 #\=)))
+
+(defun decode-char (c)
+ (ecase c
+ (#\2 2)
+ (#\1 1)
+ (#\0 0)
+ (#\- -1)
+ (#\= -2)))
+
+(defun parse-snafu (num)
+ (loop for a across (reverse num)
+ for pow = 1 then (* pow 5)
+ sum (* pow (decode-char a))))
+
+(defun write-snafu (num &optional coeffs)
+ (if (zerop num)
+ (concatenate 'string coeffs)
+ (multiple-value-bind (div rest) (floor num 5)
+ (if (> rest 2)
+ (write-snafu (1+ div) (cons (encode-char (- rest 5)) coeffs))
+ (write-snafu div (cons (encode-char rest) coeffs))))))
+
+(defun solver (filename)
+ (write-snafu (apply #'+ (mapcar #'parse-snafu (uiop:read-file-lines filename)))))
+
+(fiveam:test solutions
+ (fiveam:is (string= "2=-1=0" (solver "eg-in")))
+ (fiveam:is (string= "2-212-2---=00-1--102" (solver "input"))))