Skip to content

Instantly share code, notes, and snippets.



Last active Oct 14, 2020
What would you like to do?
Write a program that plays every possible tic-tac-toe game, and then prints the number of valid games
(defn end? [[x1 x2 x3 x4 x5 x6 x7 x8 x9]]
(and (some? x1) (= x1 x2 x3))
(and (some? x4) (= x4 x5 x6))
(and (some? x7) (= x7 x8 x9))
(and (some? x1) (= x1 x4 x7))
(and (some? x2) (= x2 x5 x8))
(and (some? x3) (= x3 x6 x9))
(and (some? x1) (= x1 x5 x9))
(and (some? x3) (= x3 x5 x7))
(and (some? x1) (some? x2) (some? x3) (some? x4) (some? x5) (some? x6) (some? x7) (some? x8) (some? x9))))
(def *games (atom 0))
(defn make-move [start sym]
(doseq [i (range 0 9)
:when (nil? (nth start i))
:let [end (assoc start i sym)]]
(if (end? end)
(swap! *games inc)
(make-move end (if (= sym :x) :o :x)))))
(make-move [nil nil nil nil nil nil nil nil nil] :x)
(println @*games)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment