Last active
October 14, 2020 10:17
-
-
Save tonsky/d2b907edb803d386f0946648956ce578 to your computer and use it in GitHub Desktop.
Write a program that plays every possible tic-tac-toe game, and then prints the number of valid games
This file contains hidden or 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
(defn end? [[x1 x2 x3 x4 x5 x6 x7 x8 x9]] | |
(or | |
(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