SICP exercise 1.03
From Drewiki
Problem
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
Solution
We can use the compound procedures square, sum-of-squares and >= that were defined earlier in sections 1.1.4 and 1.1.6 of the text:
(define (square x) (* x x)) (define (sum-of-squares x y) (+ (square x) (square y))) (define (>= x y) (not (< x y)))
Here's a procedure that implements a solution to the problem:
(define (sum-of-squares-of-two-largest x y z) (cond ((and (>= x y) (>= y z)) (sum-of-squares x y)) ((and (>= y x) (>= x z)) (sum-of-squares x y)) ((and (>= x y) (>= z y)) (sum-of-squares x z)) (else (sum-of-squares y z))))
Tests
To test the solution, we can pick 3 distinct arguments and try all their permutations:
(sum-of-squares-of-two-largest 2 3 4)
Output:
25
(sum-of-squares-of-two-largest 2 4 3)
Output:
25
(sum-of-squares-of-two-largest 3 4 2)
Output:
25
(sum-of-squares-of-two-largest 3 2 4)
Output:
25
(sum-of-squares-of-two-largest 4 3 2)
Output:
25
(sum-of-squares-of-two-largest 4 2 3)
Output:
25

