summaryrefslogtreecommitdiffstats
path: root/2021/12/two.tl
blob: 69f179ab9b9972b7fb3b21e4cdf0e81fd78744b4 (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
(defvar %cave-hash% (hash))

(defstruct cave ()
  name
  neighbors

  (:postinit (cv)
    (assert cv.name)
    (set [%cave-hash% cv.name] cv)))

(defstruct end-cave cave
  (:method visit (cv path fn)
    (push cv path)
    [fn (remq t path)]))

(defstruct start-cave cave
  (:method visit (cv path fn)
    (unless (member cv path)
      (push cv path)
      (each ((n cv.neighbors))
        n.(visit path fn)))))

(defstruct small-cave cave
  (:method visit (cv path fn)
    (let ((in-path (member cv path)))
      (when (or (not in-path)
                (not (member t path)))
        (push cv path)
        (if in-path
          (push t path))
        (each ((n cv.neighbors))
          n.(visit path fn))))))

(defstruct big-cave cave
  (:method visit (cv path fn)
    (push cv path)
    (each ((n cv.neighbors))
      n.(visit path fn))))

(defun ensure-cave (name)
  (or [%cave-hash% name]
      (set [%cave-hash% name]
           (match-case name
             ("end" (new end-cave name name))
             ("start" (new start-cave name name))
             (@[all @str chr-islower] (new small-cave name name))
             (@else (new big-cave name name))))))

(defun read-caves (: (name "input"))
  (with-stream (s (open-file name))
    (whilet ((line (get-line s)))
      (match `@a-@b` line
        (let ((ca (ensure-cave a))
              (cb (ensure-cave b)))
          (pushnew cb ca.neighbors)
          (pushnew ca cb.neighbors))))))

(defun find-paths (fn)
  (let ((start [%cave-hash% "start"]))
    (assert start)
    start.(visit nil fn)))

(defun solve (: (name "input"))
  (let (paths)
    (read-caves name)
    (find-paths (opip reverse (mapcar .name) (push @1 paths)))
    (mapdo [chain (ap join-with ",") pprinl] paths)
    (len paths)))