Skip to content

Instantly share code, notes, and snippets.

@ndonolli
Last active April 14, 2020 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndonolli/ab722fdef288cf0b260e7bf1e824b6b6 to your computer and use it in GitHub Desktop.
Save ndonolli/ab722fdef288cf0b260e7bf1e824b6b6 to your computer and use it in GitHub Desktop.
(defn check-path-win
"Checks a path for a win"
[s]
(if (apply = s)
(first s)
nil))
(defn check-win-direction
"Checks a sequence of paths in a particular direction for a win"
[dir-seq]
(first (keep check-path-win dir-seq)))
(defn get-columns
"Get sequence of vertical paths"
[matrix]
(apply map list matrix))
(defn get-down-diagonal
"Get the up->down diagonal path"
[matrix]
(->> (map-indexed list matrix)
(map #(get (last %) (first %)))
(list)))
(defn get-up-diagonal
"Get the down->up diagonal path"
[matrix]
(get-down-diagonal (reverse matrix)))
(defn check-win
"Check for tic-tac-toe win in a 2d vector matrix. Returns the winning keyword or :draw for a draw"
[matrix]
(let [rows matrix
cols (get-columns matrix)
diag-up (get-up-diagonal matrix)
diag-down (get-down-diagonal matrix)
win-checks (list rows cols diag-up diag-down)
winning-tile (->> (map check-win-direction win-checks)
(remove nil?)
(first))]
(if (nil? winning-tile)
:draw
winning-tile)))
;; Tests
(def x-wins [[:x :o :x]
[:o :x :o]
[:o :x :x]])
(def o-wins [[:x :o :x]
[:o :o :o]
[:o :x :x]])
(def draw [[:x :o :x]
[:o :x :o]
[:o :x :o]])
(check-win x-wins) ;; => :x
(check-win o-wins) ;; => :o
(check-win draw) ;; => :draw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment