From 1c147396427dbd05abadb4c1bbf9a60bb49770ec Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Sun, 3 Dec 2023 18:11:24 +0100 Subject: [AoC2023] day01 lisp fail 2nd --- AoC2023/day01/solver.lisp | 71 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 AoC2023/day01/solver.lisp (limited to 'AoC2023/day01/solver.lisp') 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)))) -- cgit v1.2.3