Created
May 27, 2010 19:41
-
-
Save asandroq/416250 to your computer and use it in GitHub Desktop.
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
;;; NQUEENS -- Compute number of solutions to 8-queens problem. | |
(define (nqueens n) | |
(define (dec-to n) | |
(let loop ((i n) (l '())) | |
(if (= i 0) l (loop (- i 1) (cons i l))))) | |
(define (try x y z) | |
(if (null? x) | |
(if (null? y) | |
1 | |
0) | |
(+ (if (ok? (car x) 1 z) | |
(try (append (cdr x) y) '() (cons (car x) z)) | |
0) | |
(try (cdr x) (cons (car x) y) z)))) | |
(define (ok? row dist placed) | |
(if (null? placed) | |
#t | |
(and (not (= (car placed) (+ row dist))) | |
(not (= (car placed) (- row dist))) | |
(ok? row (+ dist 1) (cdr placed))))) | |
(try (dec-to n) '() '())) | |
(nqueens 12) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment