public
Created

Solution to 4clojure problem 117

  • Download Gist
for_science.clj
Clojure
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
(fn solve-maze
[maze]
(let [num-rows (count maze)
num-cols (count (first maze))
char-at-pos (fn [[row col]] (get (get maze row) col))
free? (fn [p] (when-let [c (char-at-pos p)] (not= c \#)))
neighbours (fn [[row col]] (filter free? (map (fn [[delta-row delta-col]]
[(+ row delta-row)
(+ col delta-col)])
[[0 0] [0 1] [0 -1] [1 0] [-1 0]])))
intersects? (fn [ns s] (some #(contains? s %) ns))
contains-mouse? (fn [xs] (some #{\M} (map char-at-pos xs)))
contains-cheese? (fn [xs] (some #{\C} (map char-at-pos xs)))]
(loop [nodes (for [row (range num-rows) col (range num-cols)] [row col])
connected-subsets #{}]
(if nodes
(let [p (first nodes)]
(if (= (char-at-pos p) \#)
(recur (next nodes) connected-subsets)
(let [neighbouring-nodes (neighbours p)
neighbouring-subsets (filter
(partial intersects? neighbouring-nodes)
connected-subsets)
this-connected-subset (into (set neighbouring-nodes)
(reduce concat neighbouring-subsets))]
(recur (next nodes)
(conj (apply disj connected-subsets neighbouring-subsets)
this-connected-subset)))))
(boolean (some #(and (contains-mouse? %) (contains-cheese? %)) connected-subsets))))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.