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