Skip to content

Instantly share code, notes, and snippets.



Last active Jul 14, 2020
What would you like to do?
[check (fn [& sets]
(first (filter #(not (nil? %))
(fn [ss]
(let [r (first (filter #(or (= % #{:x}) (= % #{:o})) ss))]
(if r (first r) nil)))
(defn ttt [board]
(map set board)
(map set (apply map list board))
(list (set (map #(nth (nth board %) %) (range 3))))
(list (set (map #(nth (nth board %) (- 2 %)) (range 3))))
(assert (= :x (ttt [[:x :o :x] [:x :o :o] [:x :x :o]])))
(assert (= :o (ttt [[:o :x :x] [:x :o :x] [:x :o :o]])))
(assert (nil? (ttt [[:x :o :x] [:x :o :x] [:o :x :o]])))
1 - What is the code trying to accomplish?
Its an implementation of tic-tac-toe
2- Describe at a high level how it works.
ttt takes board as a parameter which is vector of vectors
line 11 (map set board) returns a lazy seq of sets[unique values] in the board horizontally
which by the way tells is there is a winner on the board row wise
line 12 (apply map list board) converts the column into rows and then do the same as on line 11
which tells if there is a winner on the board column wise or vertically
line 13 checks the board for top left diagonal winner
line 14 checks the board for the other diagonal
line 10 calls check which has rest parameter named sets and
passes the return values of forms on line 11-14
line 6 val of r is either an empty list or a list with a set with containing :x or :o
3- What feedback would you provide in a code review?
check does not need all that complexity.
I would suggest to change it to
4. (Bonus) How would you write it?
(defn mycheck
[& sets]
(first (some #(and (= (count %) 1) %) (flatten sets))))
(defn myttt [board]
(map set board)
(map set (apply map list board))
(list (set (map #(nth (nth board %) %) (range 3))))
(list (set (map #(nth (nth board %) (- 2 %)) (range 3))))))
(assert (= :x (myttt [[:x :o :x] [:x :o :o] [:x :x :o]])))
(assert (= :o (myttt [[:o :x :x] [:x :o :x] [:x :o :o]])))
(assert (nil? (myttt [[:x :o :x] [:x :o :x] [:o :x :o]])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment