J2EE之巅

 

The Clojure Program To solve N Queens Problem

The following program is about solving N-Queens problem (http://en.wikipedia.org/wiki/Eight_queens_puzzle) by Clojure. If you have the better solution in Clojure or Haskell, welcome to provide your solution.
(ns queens)
(defn conflictInRow? [queens newqueen]
  (some #(= newqueen %) queens)
)
(defn conflictInDia? [queens newqueen]
  (let [dia (count queens) 
        n1 (fn [queen] (Math/abs (- dia (.indexOf queens queen))))
        n2 (fn [queen] (Math/abs (- newqueen queen)))]
    (some #(= (n1 %) (n2 %)) queens)
   )
 )
(defn conflict? [queens newqueen]
  (or (conflictInRow? queens newqueen) (conflictInDia? queens newqueen))
 )
(def cnt (atom 0))
(defn put-queens [queens newqueen boardSize ]
  (if (= (count queens) boardSize)  
    (do
      (println queens)
      (reset! cnt (inc @cnt))
    )
    (do 
      ;(println queens)
      (if (> newqueen boardSize)
     
           (if (and (= (peek queens) boardSize) (= (count queens) 1))
               (throw (Exception. (str "That's all " @cnt)))
               (recur (pop queens) (inc (peek queens)) boardSize )
           )
     
        (if (conflict? queens newqueen)
            
             (recur queens (inc newqueen) boardSize )
             
          (do
             (put-queens (conj queens newqueen) 1 boardSize )
             (recur queens (inc newqueen) boardSize )
           )
        )
       )
      )
    )
    
)
(defn queens [boardSize] 
    (put-queens [] 1 boardSize)
 )


Chao Cai (蔡超)

Sr. Software Dev Engineer 
Amazon.com

 

posted on 2012-08-05 23:26 超越巅峰 阅读(2460) 评论(0)  编辑  收藏 所属分类: Computer Science


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(12)

随笔分类(54)

随笔档案(59)

文章分类(2)

文章档案(1)

相册

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜