首页 > 代码库 > [4Clojure]解题记录-#73

[4Clojure]解题记录-#73

Difficulty:Hard
Topics:game
A tic-tac-toe board is represented by a two dimensional vector. X is represented by :x, O is represented by :o, and empty is represented by :e. A player wins by placing three Xs or three Os in a horizontal, vertical, or diagonal row. Write a function which analyzes a tic-tac-toe board and returns :x if X has won, :o if O has won, and nil if neither player has won.
 
(= nil (__ [[:e :e :e]
               [:e :e :e]
                 [:e :e :e]]))
 
(= :x (__ [[:x :e :o]
                [:x :e :e]
                [:x :e :o]]))
 
(= :o (__ [[:e :x :e]
                [:o :o :o]
                [:x :e :x]]))
 
(= :x (__ [[:x :e :e]
                [:o :x :e]
                [:o :e :x]]))
 
(= :o (__ [[:x :e :o]
                [:x :o :e]
                [:o :e :x]]))
 
(= nil (__ [[:x :o :x]
                [:x :o :x]
                [:o :x :o]]))
 
解长度:178
(fn [m]
  (let [a (concat (apply map vector m) (seq m)
         ((fn [x] (let [g #(get-in x %) d (g [1 1])] 
              (seq [[(g [0 0]) d (g [2 2])] [(g [0 2]) d (g [2 0])]]))) m))       h (fn [k] (some #(every? #{k} %) a))]
    (if (h :x)
     :x 
         (if (h :o)
       :o 
             nil))))
基本思路,先将输入产生8个vector,3横,3纵以及两个对角线,所以
(apply map vector m)就是生成3纵; (seq m)就是3横, 
((fn  cro [x] (let [g #(get-in x %) d (g [1 1])] (seq [[(g [0 0]) d (g [2 2])] [(g [0 2]) d (g [2 0])]]))) m)) 就是两个对角线。
user=>(def input[[:x :o :x]
 [:x :o :x
                 [:o :x :o]])
user=>(apply map vector input); ([:x :x :o] [:o :o :x] [:x :x :o])
user=>(seq input); ([:x :o :x] [:x :o :x] [:o :x :o])
user=>(cro input); ([:x :o :o] [:x :o :o])
user=>(some  #(every? #{:x} %) ‘([:x :x :o] [:o :o :x] [:x :x :o])); nil
user=>(some  #(every? #{:x} %) ‘([:x :x :x] [:o :o :x] [:x :x :o])); true
user=>(some  #(every? #{:x} %) ‘([:x :x :o] [:o :o :o] [:x :x :o])); nil
最后整理,函数匿名,已经尽可能缩短字数。

[4Clojure]解题记录-#73