/
grid.clj
63 lines (52 loc) · 1.71 KB
/
grid.clj
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
(ns aoc.grid
(:require
[clojure.string :as str]
[clojure.set :as set]
[aoc.vector :refer [+v transpose]]))
(def north [-1 0])
(def north-east [-1 1])
(def east [0 1])
(def south-east [1 1])
(def south [1 0])
(def south-west [1 -1])
(def west [0 -1])
(def north-west [-1 -1])
(def right
{north east east south south west west north})
(def left
(set/map-invert right))
(defn parse
([s] (parse s identity))
([s parse-c]
(first (reduce (fn [[g y] line]
[(first (reduce (fn [[g x] c]
[(if-let [pc (parse-c c)]
(assoc g [y x] pc)
g)
(inc x)])
[g 0]
line))
(inc y)])
[{} 0]
(str/split-lines s)))))
(defn adjacent
([pos] (->> [north east south west] (map #(+v pos %))))
([pos g] (filter g (adjacent pos))))
(defn adjacent-5
([pos] (cons pos (adjacent pos)))
([pos g] (filter g (adjacent-5 pos))))
(defn adjacent-corners
([pos] (->> [north-east south-east south-west north-west] (map #(+v pos %))))
([pos g] (filter g (adjacent-corners pos))))
(defn adjacent-8
([pos] (interleave (adjacent pos) (adjacent-corners pos)))
([pos g] (filter g (adjacent-8 pos))))
(defn adjacent-9
([pos] (cons pos (adjacent-8 pos)))
([pos g] (filter g (adjacent-9 pos))))
(defn adjacent-3d
([pos] (->> [[1 0 0] [-1 0 0] [0 1 0] [0 -1 0] [0 0 1] [0 0 -1]]
(map #(+v pos %))))
([pos g] (filter g (adjacent-3d pos))))
(defn box [vs]
(map (fn [axis] [(apply min axis) (apply max axis)]) (transpose vs)))