aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day01/solver.lisp
blob: 443bcc09a0b09f081664cf80a58b3c8b7821a5b0 (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
64
65
66
67
68
69
70
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))))