Created
January 19, 2014 12:09
-
-
Save ysubach/8503969 to your computer and use it in GitHub Desktop.
Eight queens (N-queens) solution in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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