-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-42.scm
67 lines (55 loc) · 1.66 KB
/
2-42.scm
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
59
60
61
62
63
64
65
66
#lang scheme
(define nil '())
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
(define accumulate fold-right)
(define (enumerate-interval start end)
(if (> start end)
nil
(cons start (enumerate-interval (+ start 1) end))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
; solution
(define empty-board nil)
(define (safe-t? k positions) #t)
(define (safe? col positions)
(let ((candidate (car positions))
(rest (cdr positions)))
(if (null? rest)
#t
(not (contains? (lambda (x)
(conflict? x candidate))
rest)))))
(define (contains? condition list)
(cond ((not (pair? list)) #f)
((condition (car list)) #t)
(else (contains? condition (cdr list)))))
(define (conflict? a b)
(let ((ax (car a))
(ay (cadr a))
(bx (car b))
(by (cadr b)))
(or (= ax bx)
(= (abs (- ax bx)) (abs (- ay by))))))
(define (adjoin-position row col rest-of-queens)
(cons (list row col) rest-of-queens))
(define (queens board-size)
(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))
(length (queens 8))