aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--AoC2023/day01/solver.lisp38
1 files changed, 15 insertions, 23 deletions
diff --git a/AoC2023/day01/solver.lisp b/AoC2023/day01/solver.lisp
index 443bcc0..2ab61e1 100644
--- a/AoC2023/day01/solver.lisp
+++ b/AoC2023/day01/solver.lisp
@@ -14,15 +14,10 @@ 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))))))
+ (parse-integer
+ (concatenate 'string (list
+ (find-if #'digit-char-p string)
+ (find-if #'digit-char-p string :from-end t)))))
(defun translate (word)
(alexandria:eswitch (word :test (lambda (val opts) (member val opts :test #'string-equal)))
@@ -36,13 +31,14 @@ zoneight234
('("8" "eight") 8)
('("9" "nine") 9)))
-(defparameter numbers-re "[1-9]|one|two|three|four|five|six|seven|eight|nine")
+(defparameter numbers-re "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)))))
+ (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"))
(defun solver1 (lines)
(reduce #'+ lines :key #'get-pair))
@@ -55,17 +51,13 @@ zoneight234
(= 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
+ (= 55172
+ (solver1 (uiop:read-file-lines "input"))))
+ (fiveam:is (= 41 (line-value "46jtwonen")))
+ (fiveam:is
+ (= 54925
(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))))