The Clojure Program To solve N Queens Problem (Without back tracing)
Not like the previous solution here http://www.aygfsteel.com/chaocai/archive/2012/08/05/384844.htmlThe following solution not using the back tracing way is more concise and readable, but for the searching space becomes huger, the performance is much worser then the previous one.
(ns SICP.unit3)
(defn conflictInCol? [s col]
(some #(= col %) s)
)
(defn conflictInDia? [s col]
(let [dia (count s)
n1 (fn [c] (Math/abs (- dia (.indexOf s c))))
n2 (fn [c] (Math/abs (- col c)))]
(some #(= (n1 %) (n2 %)) s)
)
)
(defn safe? [s col]
(not (or (conflictInCol? s col) (conflictInDia? s col)))
)
(defn next-level-queens [solutions-for-prev-level board-size current-level]
(let [solutions (atom [])]
(doseq [s solutions-for-prev-level]
(doseq [col (range 0 board-size)]
(if (safe? s col)
(reset! solutions (cons (conj s col) @solutions))
)
)
)
(if (< current-level (dec board-size))
(recur @solutions board-size (inc current-level))
(count @solutions)
)
)
)
(defn queens [board-size]
(next-level-queens (apply vector (map #(vector %) (range 0 board-size))) board-size 1)
)(some #(= col %) s)
)
(defn conflictInDia? [s col]
(let [dia (count s)
n1 (fn [c] (Math/abs (- dia (.indexOf s c))))
n2 (fn [c] (Math/abs (- col c)))]
(some #(= (n1 %) (n2 %)) s)
)
)
(defn safe? [s col]
(not (or (conflictInCol? s col) (conflictInDia? s col)))
)
(defn next-level-queens [solutions-for-prev-level board-size current-level]
(let [solutions (atom [])]
(doseq [s solutions-for-prev-level]
(doseq [col (range 0 board-size)]
(if (safe? s col)
(reset! solutions (cons (conj s col) @solutions))
)
)
)
(if (< current-level (dec board-size))
(recur @solutions board-size (inc current-level))
(count @solutions)
)
)
)
(defn queens [board-size]
(next-level-queens (apply vector (map #(vector %) (range 0 board-size))) board-size 1)
Chao Cai (蔡超)
Sr. SDE
Amazon
posted @ 2012-11-26 12:21 超越巔峰 閱讀(2843) | 評論 (0) | 編輯 收藏