summary refs log tree commit diff
path: root/2024/d03.lisp
blob: e240ae95c9de3f794ddd5fafe5e65c07f8cb0264 (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
(in-package :aoc/2024)

(ql:quickload "cl-ppcre")

(defparameter *input/d3*
  (asdf:system-relative-pathname :advent "2024/d03.input"))

(defun readfile (filename)
  (let ((lines '()))
    (with-open-file (stream filename :direction :input)
      (loop for line = (read-line stream nil nil)
            while line
            do (push line lines)))
    (nreverse lines)))

(defun replace-with-prefix-expr (match)
  (ppcre:regex-replace "mul\\(([0-9]+),([0-9]+)\\)" match "(* \\1 \\2)"))
  
(print
  (apply '+
    (mapcar 'eval
       (mapcar #'read-from-string
          (mapcar #'replace-with-prefix-expr
             (ppcre:all-matches-as-strings "mul\\(([0-9]+),([0-9]+)\\)"
               (format nil "~{~a~}" (readfile *input/d3*))))))))
; 1795571322

(print
  (apply '+
    (mapcar 'eval
       (mapcar #'read-from-string
          (mapcar #'replace-with-prefix-expr
             (ppcre:all-matches-as-strings "mul\\(([0-9]+),([0-9]+)\\)"
                (ppcre:regex-replace-all "don't\\(\\).*?(do\\(\\)|$)"
                                         (format nil "~{~a~}" (readfile *input/d3*))
                                         "")))))))
; 103811193