sicp 2.41

Exercise 2.41.  Write a procedure to find all ordered triples of distinct positive integers ij, and k less than or equal to a given integer n that sum to a given integer s.

 

 

(define (find-triples n s)
  (filter (lambda (l)
            (if (= (sum l) s)
                #t
                #f))
          (triples n)))

(define (triples n)
  (flatmap append (flatmap append (my-triples n))))

(define (my-triples n)
  (map (lambda (i)
         (map (lambda (j)
                (map (lambda (k) (list i j k))
                     (enumerate-interval 1 (- j 1))))
              (enumerate-interval 1 (- i 1))))
       (enumerate-interval 1 n)))

(define (enumerate-interval n m)
  (if (> n m)
      '()
      (cons n (enumerate-interval (+ n 1) m))))

(define (accumulate op initial sequence)  
  (if (null? sequence)  
      initial  
      (op (car sequence)  
          (accumulate op initial (cdr sequence)))))

(define (filter predicate sequence)  
  (cond ((null? sequence) '())  
        ((predicate (car sequence))  
         (cons (car sequence)  
               (filter predicate (cdr sequence))))  
        (else (filter predicate (cdr sequence)))))

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

(define (sum l)
  (if (null? l)
      0
      (+ (car l) (sum (cdr l)))))

(triples 5)
(find-triples 9 15)

 

 

((3 2 1) (4 2 1) (4 3 1) (4 3 2) (5 2 1) (5 3 1) (5 3 2) (5 4 1) (5 4 2) (5 4 3))

((6 5 4) (7 5 3) (7 6 2) (8 4 3) (8 5 2) (8 6 1) (9 4 2) (9 5 1))

你可能感兴趣的:(SICP)