Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
From section 1.1.4 of SICP we already have:
(define (square x) (* x x)) (define (sum-of-squares x y) (+ (square x) (square y)))So all we need to do is determine which of three numbers are the largest two and then evaluate
sum-of-squares
for those. An alternate way of finding the largest two of three numbers is to find the smallest number - and then the other two numbers are the larger ones. That's how I chose to do it:(define (sum-of-squares-of-top-two a b c) (cond ((and (< a b) (< a c)) (sum-of-squares b c)) ((and (< b a) (< b c)) (sum-of-squares a c)) (else (sum-of-squares a b))))And here it is in action:
> (sum-of-squares-of-top-two 2 3 4) 25 > (sum-of-squares-of-top-two 5 4 3) 41 > (sum-of-squares-of-top-two 6 4 2) 52
This approach fails in cases where a = b < c
ReplyDelete> (sum-of-squares-of-top-two 1 1 10)
2