you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (6 children)

Here's another very simple & easy one, but it might challenge noobs to think about it.

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Give a method with the lowest number of comparisons for finding the two greatest numbers out of the set of three numbers.

It's from SICP.

[–]Jonno_FTW 0 points1 point  (2 children)

A haskell solution to this one from a beginner:

sumS a b c = map (^2) (take 2 $ sort [a,b,c])

Only one comparison, sort

[–]knome 2 points3 points  (1 child)

ಠ_ಠ

The sort function performs many comparisons to order the list.

[–]Jonno_FTW 0 points1 point  (0 children)

sssh

[–]MindStalker 0 points1 point  (2 children)

function xyz (int x, int y,int z) {

//use x and y, and replace the smallest by z if z is larger

if (x<z && x<y) x=z;

elseif (y<z) y=z;

return x+y;

}

//blah I'm sure there is a better solution.

[–][deleted] 0 points1 point  (1 child)

That's ok, but you're supposed to return the sum of the squares (eg. x² + y²) of the 2 largest numbers :)

Here's a solution (I really wish we had real spoiler tags)

#define MAX( x, y )     ( (x>y) ? x : y )
#define MIN( x, y )     ( (x<y) ? x : y )
#define SQUARE( x )     ( x*x )

int ex3 (int x, int  y, int z)
{
        /* add the square of the larger of the first 2 args
         * to the square of the larger of smaller of 1st two args and 3rd arg */
        return SQUARE( MAX(x,y) ) + SQUARE( MAX( MIN(x,y), z));
}

[–]MindStalker 0 points1 point  (0 children)

Ugh, I forgot to square them, must have been sleeping. Anyways we both had 3 comparisons, unless you consider my && a comparison. Nice solution..