diff options
-rw-r--r-- | AoC2023/day01/solver.lisp | 32 |
1 files changed, 13 insertions, 19 deletions
diff --git a/AoC2023/day01/solver.lisp b/AoC2023/day01/solver.lisp index 2ab61e1..96f26f4 100644 --- a/AoC2023/day01/solver.lisp +++ b/AoC2023/day01/solver.lisp @@ -1,5 +1,4 @@ (ql:quickload '(uiop fiveam cl-ppcre)) - (defvar eg-input "1abc2 pqr3stu8vwx a1b2c3d4e5f @@ -19,26 +18,22 @@ zoneight234 (find-if #'digit-char-p string) (find-if #'digit-char-p string :from-end t))))) +(defparameter numbers '(one two three four five six seven eight nine)) +(defparameter numbers-re (format nil "~{~(~a~)~^|~}" numbers)) + (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 "one|two|three|four|five|six|seven|eight|nine") + (or + (parse-integer word :junk-allowed t) + (1+ (position word numbers :test #'string-equal)))) (defun line-value (string) - (let ((first (cl-ppcre:scan-to-strings (format nil "[1-9]|~a" numbers-re) string)) - (last (reverse (cl-ppcre:scan-to-strings (format nil "[1-9]|~a" (reverse numbers-re)) (reverse string))))) - (+ (* 10 (translate first)) (translate last)))) - -(cl-ppcre:scan-to-strings (reverse numbers-re) (reverse "4nineeightseven2")) + (let (all) + (cl-ppcre:do-register-groups (m) + ((format nil "(?=([1-9]|~a))" numbers-re) string) + (push m all)) + (setf all (nreverse all)) + (+ (* 10 (translate (first all))) + (translate (car (last all)))))) (defun solver1 (lines) (reduce #'+ lines :key #'get-pair)) @@ -60,4 +55,3 @@ zoneight234 (fiveam:is (= 54925 (solver2 (uiop:read-file-lines "input"))))) - |