Skip to content

Instantly share code, notes, and snippets.

@ppsdatta
Created May 1, 2021 07:51
Show Gist options
  • Save ppsdatta/cad15e473fe581f50273fb3d94e32236 to your computer and use it in GitHub Desktop.
Save ppsdatta/cad15e473fe581f50273fb3d94e32236 to your computer and use it in GitHub Desktop.
Brute force N queens problem solver - SBCL gives up after 7x7 board
(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