aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2023/day08/solver.lisp
blob: b552ef5ef6f1b28b6cfab2d629bf64b93d2713ae (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
(ql:quickload '(fiveam str))
                                        ;12:13
                                        ;
(defparameter eg-input "LLR

AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)")

(defun parse-input (lines)
  (let ((graph (make-hash-table)))
    (destructuring-bind (instructions blank . nodes) lines
      (declare (ignorable blank))
      (dolist (line nodes)
        (with-input-from-string (in (str:replace-all "=|," "" line :regex t))
          (setf
           (gethash (read in) graph)
           (read in))))
      (values instructions graph))))

(defun traverse (instructions graph location steps)
  (if (eq location 'ZZZ)
      (values steps location)
      (let ((new-steps (loop
                         for direction across instructions
                         do
                            (setf location
                                  (ecase direction
                                    (#\L (first (gethash location graph)))
                                    (#\R (second (gethash location graph)))))
                         count direction until (eq location 'ZZZ))))
        (traverse instructions graph location (+ steps new-steps)))))

(defun solver1 (lines)
  (multiple-value-bind (instructions graph)
      (parse-input lines)
    (traverse instructions graph 'AAA 0)))

(fiveam:test solutions
  (fiveam:is (= 6 (solver1 (uiop:split-string eg-input :separator '(#\Newline)))))
  (fiveam:is (= 19199 (solver1 (uiop:read-file-lines "input")))))