Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

I feel retarded, /prog/

Name: Anonymous 2010-01-14 22:05

I'm on SICP, and I've never programmed before, and I'm stuck on the most basic of SICP exercises...

Exercise 1.3.  Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

Being the weakling that I am, I turned to google for help, and returned this program:

(define (square x) (* x x))
 
 (define (sum-of-squares x y)
   (+ (square x) (square y)))
 
 (define (largest-two-of-three x y z)
   (if (>= x y)
       (sum-of-squares x (if (>= y z) y z))
       (sum-of-squares y (if (>= x z) x z))))


It's the largest part I'm having problems with:
It defines the function "largest-two-of-three" with variables 'x', 'y' and 'z'. It goes on to state the parameters of the function as, if x is greater than y, do the sum of squares for x and, if y is greater than or equal to z, y and z, and if y isn't larger or equal to z, then z? Or, if x is less than y, do the sum of squares for y and, if x is greater than or equal to z, x, if not, z?

I know this is a really sad place to be stuck on, but I want to learn how to program rather much, and I won't let this stop me

Name: Anonymous 2010-01-14 23:01

You could say it's a sort expanded using a human macroexpander.
In a general case:given an arbitrary number of integers, return the sum of squares of the first n numbers, you would just use a sort function to sort the entire list/array/sequence and then just calculate the sum of squares of that part of the list. Here's a general, but slower solution I just wrote on 2 minutes:


(defun n-biggest-numbers (sequence n)
  (subseq (sort sequence #'>) 0 n))

(defun square (x) (* x x))
(defun sum-of-squares (numbers)
  (apply #'+ (map 'list #'square numbers)))

(defun sum-of-squares-of-n-biggest-numbers (sequence &optional (n 2))
  (sum-of-squares (n-biggest-numbers sequence n)))

Excuse my CL, but I don't have any Scheme implementations installed on this box.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List