乐正

Actions speak louder than words.

Sicp-ex2-41

问题

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

解答

可以利用练习2.40定义的unique-pairs过程来生成三元组:

练习2.41 (ex2-41.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
;; Happy hacking, Yuez - Emacs ♥ you!

(define (sum-equal-tuple n s)
  (define (sum-tuple-equal-s? tuple)
    (= (+ (car tuple) (cadr tuple) (cadr (cdr tuple))) s))

  (filter sum-tuple-equal-s?
          (flatmap (lambda (i)
                     (map (lambda (j)
                            (cons i j))
                          (unique-pairs (- i 1))))
                   (enumerate-interval 1 n))))

测试

1
2
3
4
5
(sum-equal-tuple 10 8)
;Value 20: ((4 3 1) (5 2 1))

(sum-equal-tuple 12 24)
;Value 21: ((9 8 7) (10 8 6) (10 9 5) (11 7 6) (11 8 5) (11 9 4) (11 10 3) (12 7 5) (12 8 4) (12 9 3) (12 10 2) (12 11 1))

draft

« sicp-ex2-40 sicp-ex2-42 »

Comments