LoginSignup
1
0

More than 5 years have passed since last update.

GaucheでNクイーン

Posted at
nqueen.scm
#!/usr/local/bin/gosh

(define count 0)

(define (solve? num ls)
  (let loop ((ls ls)(n 1))
    (cond
      ((null? ls)#t)
      ((= (abs (- num (car ls))) n)
       #f)
      (else (loop (cdr ls)(+ n 1))))))

(define (check? lst)
  (let loop ((lst lst))
    (cond
      ((null? (cdr lst))#t)
      ((solve? (car lst) (cdr lst))
       (loop (cdr lst)))
      (else #f))))

(define (queen lst)
  (let loop ((lst lst)(result '()))
    (if (null? lst)
      (and (check? (reverse result))
           (set! count (+ count 1))
           (print (reverse result)))
      (for-each (lambda(x)(loop (delete x lst) (cons x result))) lst)))
  (display count)
  (newline))

(define (main args)
  (display ">> ")(flush)
  (let ((n (read)))
    (queen (iota n 0))))

実行例

.>> 5
(0 2 4 1 3)
(0 3 1 4 2)
(1 3 0 2 4)
(1 4 2 0 3)
(2 0 3 1 4)
(2 4 1 3 0)
(3 0 2 4 1)
(3 1 4 2 0)
(4 1 3 0 2)
(4 2 0 3 1)
10

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0