summaryrefslogtreecommitdiffstats
path: root/2021/09/code.tl
blob: a0e223e7fc76b63816c6660e815a104fcbdc2212 (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
(defstruct board ()
  w h a

  (:method lambda (me x y)
    (if (or (minusp x)
            (minusp y)
            (<= me.w x)
            (<= me.h y))
      #\9
      [[me.a y] x]))

  (:method lambda-set (me x y nv)
    (set [[me.a y] x] nv)))

(defun read-input (: (name "input"))
  (flow (file-get-lines name)
    vec-list
    (new board
         h (len @1)
         w (len (first @1))
         a @1)))

;;-----------------------------------------------------------------------------

(defun solve-one (bo)
  (sum-each-prod ((y 0..bo.h)
                  (x 0..bo.w))
    (let ((c [bo x y])
          (u [bo x (pred y)])
          (d [bo x (succ y)])
          (l [bo (pred x) y])
          (r [bo (succ x) y]))
      (if (and (< c u) (< c d) (< c l) (< c r))
        (+ 1 (chr-digit c))
        0))))

;;-----------------------------------------------------------------------------

(defmeth board basin-size (bo x y)
  (caseq [bo x y]
    ((#\9 #\space) 0)
    (t (set [bo x y] #\space)
       (+ 1
          bo.(basin-size x (pred y))
          bo.(basin-size x (succ y))
          bo.(basin-size (pred x) y)
          bo.(basin-size (succ x) y)))))

(defun solve-two (bo)
  (flow
    (build
      (each-prod ((y 0..bo.h)
                  (x 0..bo.w))
        (let* ((bs bo.(basin-size x y)))
          (if (plusp bs)
            (add bs)))))
    sort
    (nthlast 3)
    prod))