码迷,mamicode.com
首页 > 其他好文 > 详细

[4Clojure]解题记录-#73

时间:2014-11-26 20:50:11      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   ar   color   os   sp   on   div   

Difficulty: Hard
Topics: game
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

标签:style   http   io   ar   color   os   sp   on   div   

原文地址:http://www.cnblogs.com/zjfu/p/4124743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!