-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.42.rkt
77 lines (67 loc) · 2.15 KB
/
2.42.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#lang sicp
;; Exercise 2.42:
;; The “eight-queens puzzle” asks how to place eight queens on a chessboard
;; so that no queen is in check from any other (i.e., no two queens are in the same row, column, or diagonal).
(define (queens board-size)
(define (queen-cols k)
(if (= k 0) ;; end at k = 0
(list empty-board) ;; end with an empty board
(filter ;; if it isn't the last col (k not 0), filter the rows
(lambda (positions)
(safe? k positions)) ;; check if this queen is safe
(flatmap
(lambda (rest-of-queens) ;; the rest of the queen already on the board
(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)) ;; Start from n
(define (safe? k positions)
(null? (filter (lambda (p)
(+))
positions)))
(define (adjoin-position new-row k rest-of-queens)
(cons (list new-row k) rest-of-queens))
;; The empty board is nil
(define empty-board nil)
;; required
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1)
(append (cdr list1)
list2))))
(define (flatmap proc seq)
(accumulate append nil (map proc seq)))
(define (filter predicate sequence)
(cond ((null? sequence) nil)
((predicate (car sequence))
(cons (car sequence)
(filter predicate
(cdr sequence))))
(else (filter predicate
(cdr sequence)))))
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op
initial
(cdr sequence)))))
(define (enumerate-interval low high)
(if (> low high)
nil
(cons low
(enumerate-interval
(+ low 1)
high))))