1;;; NQUEENS -- Compute number of solutions to 8-queens problem.
2;; 2006/08 -- renamed `try' to `try-it' to avoid Bigloo collision (mflatt)
3
4(define trace? #f)
5
6(define (nqueens n)
7
8  (define (one-to n)
9    (let loop ((i n) (l '()))
10      (if (= i 0) l (loop (- i 1) (cons i l)))))
11
12  (define (try-it x y z)
13    (if (null? x)
14      (if (null? y)
15        (begin (if trace? (begin (write z) (newline))) 1)
16        0)
17      (+ (if (ok? (car x) 1 z)
18           (try-it (append (cdr x) y) '() (cons (car x) z))
19           0)
20         (try-it (cdr x) (cons (car x) y) z))))
21
22  (define (ok? row dist placed)
23    (if (null? placed)
24      #t
25      (and (not (= (car placed) (+ row dist)))
26           (not (= (car placed) (- row dist)))
27           (ok? row (+ dist 1) (cdr placed)))))
28
29  (try-it (one-to n) '() '()))
30
31(let ((input (with-input-from-file "input.txt" read)))
32  (time
33   (let loop ((n 500) (v 0))
34     (if (zero? n)
35         v
36         (loop (- n 1) (nqueens (if input 8 0)))))))
37