|
| 1 | +(ns go-counting) |
| 2 | + |
| 3 | +(defn grid->graph [xs] |
| 4 | + (->> (for [x (-> xs count range), y (-> xs first count range)] |
| 5 | + (case (get-in xs [x y]) |
| 6 | + \W [[y x] :white] |
| 7 | + \B [[y x] :black] |
| 8 | + \space [[y x] :free])) |
| 9 | + (into {}))) |
| 10 | + |
| 11 | +(defn neighbors [pred stones [x y]] |
| 12 | + (->> [[0 1] [0 -1] [1 0] [-1 0]] |
| 13 | + (map (fn [[j k]] [(+ x j) (+ y k)])) |
| 14 | + (filter (comp pred stones)))) |
| 15 | + |
| 16 | +(defn territory-of [stones [x y]] |
| 17 | + (if (= :free (stones [x y])) |
| 18 | + (letfn [(f [[seen frontier]] |
| 19 | + (let [nseen (reduce conj seen frontier)] |
| 20 | + [nseen (->> frontier |
| 21 | + (mapcat #(neighbors #{:free} stones %)) |
| 22 | + (filter (complement nseen)))]))] |
| 23 | + (->> [#{} [[x y]]] |
| 24 | + (iterate f) |
| 25 | + (drop-while (comp seq second)) |
| 26 | + (ffirst))) |
| 27 | + #{})) |
| 28 | + |
| 29 | +(defn territory-owner [stones territory] |
| 30 | + (->> territory |
| 31 | + (mapcat (partial neighbors #{:black :white} stones)) |
| 32 | + (map stones) |
| 33 | + (#(cond (empty? %) nil |
| 34 | + (every? (partial = :black) %) :black |
| 35 | + (every? (partial = :white) %) :white |
| 36 | + :else nil)))) |
| 37 | + |
| 38 | +(defn territory [grid [x y]] |
| 39 | + (let [stones (grid->graph grid) |
| 40 | + territory (territory-of stones [x y])] |
| 41 | + (if (nil? (stones [x y])) |
| 42 | + (throw (new js/Error "Invalid coordinate!")) |
| 43 | + {:stones territory :owner (territory-owner stones territory)}))) |
| 44 | + |
| 45 | +(defn territories [grid] |
| 46 | + (let [territories (->> grid grid->graph keys (map (partial territory grid))) |
| 47 | + territory-for #(->> territories (filter (comp % :owner)) (map :stones) (reduce concat) set)] |
| 48 | + {:black-territory (territory-for (partial = :black)) |
| 49 | + :white-territory (territory-for (partial = :white)) |
| 50 | + :null-territory (territory-for nil?)})) |
0 commit comments