aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day01/solver.lisp
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2023-12-03 18:11:24 +0100
committerOscar Najera <hi@oscarnajera.com>2023-12-03 18:11:24 +0100
commit1c147396427dbd05abadb4c1bbf9a60bb49770ec (patch)
tree37b50feeffe88ac241ca48001b19e7b267103ccc /AoC2023/day01/solver.lisp
parentb67dd423cd43b056c19838144e39963d3ba02fb0 (diff)
downloadscratch-1c147396427dbd05abadb4c1bbf9a60bb49770ec.tar.gz
scratch-1c147396427dbd05abadb4c1bbf9a60bb49770ec.tar.bz2
scratch-1c147396427dbd05abadb4c1bbf9a60bb49770ec.zip
[AoC2023] day01 lisp fail 2nd
Diffstat (limited to 'AoC2023/day01/solver.lisp')
-rw-r--r--AoC2023/day01/solver.lisp71
1 files changed, 71 insertions, 0 deletions
diff --git a/AoC2023/day01/solver.lisp b/AoC2023/day01/solver.lisp
new file mode 100644
index 0000000..443bcc0
--- /dev/null
+++ b/AoC2023/day01/solver.lisp
@@ -0,0 +1,71 @@
+(ql:quickload '(uiop fiveam cl-ppcre))
+
+(defvar eg-input "1abc2
+pqr3stu8vwx
+a1b2c3d4e5f
+treb7uchet")
+
+(defvar eg-input2 "two1nine
+eightwothree
+abcone2threexyz
+xtwone3four
+4nineeightseven2
+zoneight234
+7pqrstsixteen")
+
+(defun get-pair (string)
+ (loop with first and last and num = 0
+ for c across string
+ when (digit-char-p c)
+ do (progn (setf last c)
+ (when (= 1 (incf num))
+ (setf first c)))
+ finally (return
+ (parse-integer
+ (concatenate 'string (list first last))))))
+
+(defun translate (word)
+ (alexandria:eswitch (word :test (lambda (val opts) (member val opts :test #'string-equal)))
+ ('("1" "one") 1)
+ ('("2" "two") 2)
+ ('("3" "three") 3)
+ ('("4" "four") 4)
+ ('("5" "five") 5)
+ ('("6" "six") 6)
+ ('("7" "seven") 7)
+ ('("8" "eight") 8)
+ ('("9" "nine") 9)))
+
+(defparameter numbers-re "[1-9]|one|two|three|four|five|six|seven|eight|nine")
+
+(defun line-value (string)
+ (let ((res
+ (mapcar #'translate
+ (cl-ppcre:all-matches-as-strings numbers-re string))))
+ (+ (* 10 (car res)) (car (last res)))))
+
+(defun solver1 (lines)
+ (reduce #'+ lines :key #'get-pair))
+
+(defun solver2 (lines)
+ (reduce #'+ lines :key #'line-value :start 0))
+
+(fiveam:test solutions
+ (fiveam:is
+ (= 142
+ (solver1 (uiop:split-string eg-input :separator '(#\Newline)))))
+ (fiveam:is
+ (= 55172
+ (solver1 (uiop:read-file-lines "input"))))
+ (fiveam:is
+ (= 281
+ (solver2 (uiop:split-string eg-input2 :separator '(#\Newline)))))
+ (fiveam:is
+ (= 54953
+ (solver2 (uiop:read-file-lines "input")))))
+
+(uiop:with-output-file (sol "solut")
+ (let ((ser 0))
+ (loop for line in (uiop:read-file-lines "input")
+ for val = (line-value line) do
+ (format sol "~d ~d ~a~%" (incf ser val) val line))))