Last active
February 13, 2018 09:32
-
-
Save reborg/580485630ac5c31746ae190c3265c556 to your computer and use it in GitHub Desktop.
The ultimate searching winning position tic-tac-toe algo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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