Skip to content

Instantly share code, notes, and snippets.

@featheredtoast
Last active October 6, 2015 20:13
Show Gist options
  • Save featheredtoast/b74cb23f72977cd329f2 to your computer and use it in GitHub Desktop.
Save featheredtoast/b74cb23f72977cd329f2 to your computer and use it in GitHub Desktop.
(defn tic-tac
[b]
(let [winning-moves [[[0 0] [0 1] [0 2]]
[[1 0] [1 1] [1 2]]
[[2 0] [2 1] [2 2]]
[[0 0] [1 0] [2 0]]
[[0 1] [1 1] [2 1]]
[[0 2] [1 2] [2 2]]
[[0 0] [1 1] [2 2]]
[[2 0] [1 1] [0 2]]]
analyze-moves (fn
[b potential-win]
(let [analyze (fn [coordinate] (nth (nth b (first coordinate)) (second coordinate)))
potential-win-values (map analyze potential-win)]
(cond (apply = :x potential-win-values) :x
(apply = :o potential-win-values) :o
true nil)))]
(->> winning-moves
(map (partial analyze-moves b))
(drop-while nil?)
first)))
(defn tic-tac2
[[[a b c] [d e f] [g h i]]]
(->> [[a b c] [d e f] [g h i]
[a d g] [b e h] [c f i]
[a e i] [c e g]]
(filter (partial apply =))
(map first)
(drop-while (partial = :e))
first))
(defn win-tic-tac
[side b]
(let [empty-spaces (for [x (range 3) y (range 3)
:when (= :e (get-in b [x y]))]
[x y])
play-move (fn [coordinate] (assoc-in b coordinate side))
check-win (fn
[[[a b c] [d e f] [g h i]]]
(->> [[a b c] [d e f] [g h i]
[a d g] [b e h] [c f i]
[a e i] [c e g]]
(filter (partial apply =))
(map first)
(drop-while (partial = :e))
first))]
(->> empty-spaces
(filter #(= side ((comp check-win play-move) %)))
(into #{}))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment