SICP Exercise 2.41

Question

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

Answer

Very similar to our unique-pairs procedure in exercise 2.40.

(define (unique-triples n)
  (flatmap
   append
   (flatmap
    append
    (map (λ (i)
           (map (λ (j)
                  (map (λ (k)
                         (list i j k))
                       (enumerate-interval 1 (- j 1))))
                (enumerate-interval 2 (- i 1))))
         (enumerate-interval 3 n)))))

; testing:
(unique-triples 5)

Results:

((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))