summaryrefslogtreecommitdiffstats
path: root/net/ricketyspace/sicp/two/fortytwo.scm
blob: 7ccf00e728aeefd42fc1a0eacc5423e5d7eca521 (plain) (blame)
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
;;;;
;;;; License: CC0-1.0
;;;;

(define-module (net ricketyspace sicp two fortytwo)
  #:export (safe?))

(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)
      '()
      (cons low (enumerate-interval (+ low 1) high))))

(define (flatmap proc seq)
  (accumulate append '() (map proc seq)))

(define (position-row pos)
  (car pos))

(define (position-col pos)
  (car (cdr pos)))

(define (abs-diff pos-a pos-b)
  (cons (abs (- (position-row pos-a) (position-row pos-b)))
        (abs (- (position-col pos-a) (position-col pos-b)))))

(define (safe? k positions)
  (define (kth-position)
    (let ((kpos (filter (lambda (pos)
                          (= (position-col pos) k))
                        positions)))
      (if (not (null? kpos)) (car kpos) #f)))
  (define (same-row?)
    (let* ((kpos (kth-position))
          (in-same-row (filter (lambda (pos)
                                 (and (not (equal? pos kpos))
                                      (= (position-row pos)
                                         (position-row kpos))))
                               positions)))
      (if (null? in-same-row) #f #t)))
  (define (same-diagonal?)
    (let* ((kpos (kth-position))
           (in-same-diag (filter (lambda (pos)
                                   (let ((diff (abs-diff pos kpos)))
                                     (and (not (equal? pos kpos))
                                          (= (car diff) (cdr diff)))))
                                 positions)))
      (if (null? in-same-diag) #f #t)))
  (not (or (same-row?) (same-diagonal?))))