Skip to content

Instantly share code, notes, and snippets.

Created September 27, 2011 06:17
Show Gist options
  • Save anonymous/1244457 to your computer and use it in GitHub Desktop.
Save anonymous/1244457 to your computer and use it in GitHub Desktop.
;; amalloy's solution to Analyze Reversi
;; https://4clojure.com/problem/124
(fn [board color]
(let [enemy? #{('{b w, w b} color)}
h (count board)
w (count (first board))
dims [h w]
valid? (fn [pos]
(every? true?
(map < [-1 -1] pos dims)))
piece #(get-in board %)
vacant? (comp #{'e} piece)
neighbors (let [deltas [-1 0 1]]
(for [y deltas, x deltas
:when (not= y x 0)]
[y x]))
pointer (fn [pos dir]
(->> pos
(iterate #(map + dir %))
(take-while valid?)))
impacted (fn [pos dir]
(let [tokens (pointer pos dir)
[captured end] (split-with (comp not #{color} first)
(map (juxt piece identity)
(rest tokens)))]
(when (and (= color (ffirst end))
(every? (comp enemy? first) captured))
(map second captured))))]
(into {}
(for [y (range h), x (range w), :let [pos [y x]]
:when (vacant? pos)
:let [flipped (for [n neighbors]
(impacted pos n))]
:when (some seq flipped)]
[pos (set (apply concat flipped))]))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment