-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.42-eight-queens.rkt
58 lines (47 loc) · 1.55 KB
/
2.42-eight-queens.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#lang racket/base
(require racket/trace)
(require racket/include)
(include "1/abs.rkt")
(include "2/accumulate.rkt")
(include "2/enumerate.rkt")
(include "2/for-each.rkt")
(include "2/list.rkt")
(trace-define (queen board-size)
(trace-define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
(define empty-board '())
(define (adjoin-position row col rest-of-queens)
(cons (list row col) rest-of-queens))
(define (safe? k positions)
(if (= (length positions) 1)
#t
(if (attack? (k-queen positions) (first-queen positions))
#f
(safe? k (remove (first-queen positions) positions)))))
(define (k-queen positions)
(car positions))
(define (first-queen positions)
(cadr positions))
(define (attack? q1 q2)
(or (= (row q1) (row q2))
(= (abs (- (row q1) (row q2)))
(abs (- (col q1) (col q2))))))
(define (row position)
(car position))
(define (col position)
(cadr position))
(define (remove item sequence)
(filter (lambda (x) (not (equal? x item)))
sequence))
(define args (current-command-line-arguments))
(queen (string->number(vector-ref args 0)))