Created
May 1, 2021 07:51
-
-
Save ppsdatta/cad15e473fe581f50273fb3d94e32236 to your computer and use it in GitHub Desktop.
Brute force N queens problem solver - SBCL gives up after 7x7 board
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
(defun all-pos (n) | |
(loop for i from 0 to (- n 1) | |
append (loop for j from 0 to (- n 1) | |
collect (cons i j)))) | |
(defun single-queen (n) | |
(loop for i in (all-pos n) | |
collect (list i))) | |
(defun safep (p moves) | |
(every (lambda (m) | |
(and (not (= (car p) (car m))) | |
(not (= (cdr p) (cdr m))) | |
(not (= (abs (- (car p) (car m))) | |
(abs (- (cdr p) (cdr m))))))) | |
moves)) | |
(defun merge1 (p all-moves) | |
(let ((mergeables (remove-if-not (lambda (ms) (safep p ms)) all-moves))) | |
(mapcar (lambda (ms) (cons p ms)) mergeables))) | |
(defun merge-all (ps all-moves) | |
(loop for p in ps | |
append (merge1 p all-moves))) | |
(defun queen1 (n l) | |
(let* ((s (single-queen l)) | |
(p (all-pos l)) | |
(r s)) | |
(dotimes (i (- n 1)) | |
(setq r (merge-all p r))) | |
r)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment