2.41

练习 2.41 请写出一个过程,它能产生出所有小于等于给定整数n的正的相异整数i、j和k的有序三元组,使每个三元组的三个元之和等于给定的整数s。


首先,定义 accumulate

 
(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence))) 
      )
  )
x
 
#<undef>

然后,定义 flatmap

 
(define (flatmap proc seq)
  (accumulate append '()  (map proc seq)))
 
#<undef>
 
(define (enumerate-interval low high)
  (if (> low high)
      '()
      (cons low (enumerate-interval (+ low 1) high))))
(define (pairs n)
  (define interval (enumerate-interval 1 n))
  (flatmap  
   (lambda (x) 
     (filter 
      (lambda (lst) (< (car lst) (cadr lst)))
      (map 
       (lambda (y) (list x y)) 
       (remove x interval))))
   interval))
(pairs 10)
 
((1 2) (1 3) (1 4) (1 5) (1 6) (1 7) (1 8) (1 9) (1 10) (2 3) (2 4) (2 5) (2 6) (2 7) (2 8) (2 9) (2 10) (3 4) (3 5) (3 6) (3 7) (3 8) (3 9) (3 10) (4 5) (4 6) (4 7) (4 8) (4 9) (4 10) (5 6) (5 7) (5 8) (5 9) (5 10) (6 7) (6 8) (6 9) (6 10) (7 8) (7 9) (7 10) (8 9) (8 10) (9 10))
 
(define (make-pair-sum pair)
  (list (car pair) (cadr pair) (+ (car pair) (cadr pair))))
(define (s-sum-pairs n s)
  (map 
   make-pair-sum 
   (filter 
    (lambda (pair) (= (+ (car pair) (cadr pair)) s))
    (pairs n)))
  )
(s-sum-pairs 10 11)
 
((1 10 11) (2 9 11) (3 8 11) (4 7 11) (5 6 11))

results matching ""

    No results matching ""