Skip to content

Instantly share code, notes, and snippets.

@reborg
Last active February 13, 2018 09:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reborg/580485630ac5c31746ae190c3265c556 to your computer and use it in GitHub Desktop.
Save reborg/580485630ac5c31746ae190c3265c556 to your computer and use it in GitHub Desktop.
The ultimate searching winning position tic-tac-toe algo.
;; Playing with conciness and expressivity in Clojure.
;; Not an exercise in efficiency, there are better solutions.
;; It works for different NxN sizes and it's lazy, stopping
;; at the first winning combination for the given player.
(defn winner? [player game]
(let [size (count game)
idxs (range size)]
(->> [[x idx] [idx y] [idx idx] [idx (- (dec size) idx)]]
(map (fn [[x y]] ((game x) y)))
(for [x idxs y idxs idx idxs])
(apply mapcat list)
(partition size)
(some #(apply = player %)))))
(winner? :x [[:x :o nil]
[nil :x :o]
[:o :x :x]])
;; true
(winner? :o [[:o :o :x :x]
[:x :x :o :o]
[:o :x :o :x]
[:o :x :o :x]])
;; nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment