aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day01/solver.lisp
blob: 96f26f4e4891193b043476b2e65a7578b50139a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
(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)
  (parse-integer
   (concatenate 'string (list
                         (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)
  (or
   (parse-integer word :junk-allowed t)
   (1+ (position word numbers :test #'string-equal))))

(defun line-value (string)
  (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))

(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
   (= 281
      (solver2 (uiop:split-string eg-input2 :separator '(#\Newline)))))
  (fiveam:is
   (= 55172
      (solver1 (uiop:read-file-lines "input"))))
  (fiveam:is (= 41 (line-value "46jtwonen")))
  (fiveam:is
   (= 54925
      (solver2 (uiop:read-file-lines "input")))))