aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day01/solver.lisp
blob: 2ab61e165755211b441b92669838e5d7c7b961c3 (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
58
59
60
61
62
63
(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)))))

(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")

(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"))

(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")))))