Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created May 23, 2011 05:54
Show Gist options
  • Save kencoba/986288 to your computer and use it in GitHub Desktop.
Save kencoba/986288 to your computer and use it in GitHub Desktop.
solve n_queen problem
(use '[clojure.contrib.combinatorics :only (permutations)])
(defn- valid? [board]
{:pre [(vector? board)]}
(let [n (count board)]
(every?
#(let [[i j] %] (and (not= (board i) (board j))
(not= (- i (board i)) (- j (board j)))
(not= (+ i (board i)) (+ j (board j)))))
(for [i (range n) j (range n) :when (not= i j)] (vector i j)))))
(defn n-queen [n]
{pre [(number? n)]}
(for [board (permutations (range n))
:when (valid? (vec board))]
(vec board)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment