Skip to content

Instantly share code, notes, and snippets.

@ysubach
Created January 19, 2014 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysubach/8503969 to your computer and use it in GitHub Desktop.
Save ysubach/8503969 to your computer and use it in GitHub Desktop.
Eight queens (N-queens) solution in Clojure
(def board-size 8)
(defn qtest [qcol qvect]
"Test if position `qcol` is okay for addition to `qvect`"
(defn f [x] (let [[row col] x]
(or
(= qcol col)
(= qcol (- col (+ row 1)))
(= qcol (+ col (+ row 1))))))
(empty? (filter f (map-indexed vector (rseq qvect)))))
(defn qsolve [qvect]
"Recursively find solution based on initial `qvect` board config"
(doseq [p (range board-size)]
(if (qtest p qvect)
(let [qnew (conj qvect p)]
(if (= (count qnew) board-size) (println qnew) (qsolve qnew))))))
(qsolve []) ; start solution finding from empty board config
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment