tags:

views:

121

answers:

3

Here is a problem Statement :

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

The solution is long,

(defn large [x y]
(if (> x y) x y))

(defn large-3 [x y z]
(if(> (large x y) z) (large x y) z))

(defn small [x y]
(if (< x y) x y))

(defn small-3 [x y z]
(if (< (small x y) z ) (small x y) z))

(defn second-largest [x y z]
  (let [greatest (large-3 x y z)
    smallest (small-3 x y z)]
    (first (filter #(and (> greatest %) (< smallest %)) [x y z]))))

(defn square [a]
  (* a a)
)

(defn sum-of-square [x y z]
  (+ (square (large-3 x y z)) (square (second-largest x y z))))

Just wanted to know what different/succinct ways this problem can be solved in Clojure.

+3  A: 

(See a sequence version of the problem together with a lazy solution in my second update to this answer below.)

(defn square [n]
  (* n n))

;; generalises easily to larger numbers of arguments
(defn sum-of-larger-squares [x y z]
  (apply + (map square (take 2 (reverse (sort [x y z]))))))

;; shorter; generalises easily if you want
;; 'the sum of the squares of all numbers but n smallest'
(defn sum-of-larger-squares [x y z]
  (apply + (map square (drop 1 (sort [x y z])))))

Update:

To expand on the comments from the above, the first version's straighforward generalisation is to this:

(defn sum-of-larger-squares [n & xs]
  (apply + (map square (take n (reverse (sort xs))))))

The second version straightforwardly generalises to the version Arthur posted in the meantime:

(defn sum-of-larger-squares [n & xs]
  (apply + (map square (drop n (sort xs)))))

Also, I've seen exactly the same problem being solved in Scheme, possibly even on SO... It included some fun solutions, like one which calculated the some of all three squares, then subtracted the smallest square (that's very straightforward to express with Scheme primitives). That's 'unefficient' in that it calculates the one extra square, but it's certainly very readable. Can't seem to find the link now, unfortunately.

Update 2:

In response to Arthur Ulfeldt's comment on the question, a lazy solution to a (hopefully fun) different version of the problem. Code first, explanation below:

(use 'clojure.contrib.seq-utils) ; recently renamed to clojure.contrib.seq

(defn moving-sum-of-smaller-squares [pred n nums]
  (map first
       (reductions (fn [[current-sum [x :as current-xs]] y]
                     (if (pred y x)
                       (let [z (peek current-xs)]
                         [(+ current-sum (- (* z z)) (* y y))
                          (vec (sort-by identity pred (conj (pop current-xs) y)))])
                       [current-sum
                        current-xs]))
                   (let [initial-xs (vec (sort-by identity pred (take n nums)))
                         initial-sum (reduce + (map #(* % %) initial-xs))]
                     [initial-sum initial-xs])
                   (drop n nums))))

The clojure.contrib.seq-utils (or c.c.seq) lib is there for the reductions function. iterate could be used instead, but not without some added complexity (unless one would be willing to calculate the length of the seq of numbers to be processed at the start, which would be at odds with the goal of remaining as lazy as possible).

Explanation with example of use:

user> (moving-sum-of-smaller-squares < 2 [9 3 2 1 0 5 3])
(90 13 5 1 1 1)

;; and to prove laziness...
user> (take 2 (moving-sum-of-smaller-squares < 2 (iterate inc 0)))
(1 1)

;; also, 'smaller' means pred-smaller here -- with
;; a different ordering, a different result is obtained
user> (take 10 (moving-sum-of-smaller-squares > 2 (iterate inc 0)))
(1 5 13 25 41 61 85 113 145 181)

Generally, (moving-sum-of-smaller-squares pred n & nums) generates a lazy seq of sums of squares of the n pred-smallest numbers in increasingly long initial fragments of the original seq of numbers, where 'pred-smallest' means smallest with regard to the ordering induced by the predicate pred. With pred = >, the sum of n greatest squares is calculated.

This function uses the trick I mentioned above when describing the Scheme solution which summed three squares, then subtracted the smallest one, and so is able to adjust the running sum by the correct amount without recalculating it at each step.

On the other hand, it does perform a lot of sorting; I find it's not really worthwhile to try and optimise this part, as the seqs being sorted are always n elements long and there's a maximum of one sorting operation at each step (none if the sum doesn't require adjustment).

Michał Marczyk
need to square each number before summing it. could swap out + for #(+ (* %1 %1) (* %2 %2)) to make it read more like (apply sum-of-squares ...)
Arthur Ulfeldt
I like your generalization of the problem :)
Arthur Ulfeldt
Yes, I forgot the squaring initially, but had it corrected within like 15 seconds... You've been fast to catch me on this one. :-) As for the anonymous function which sums and squares its arguments, it's ok if you're squaring two numbers, but can't be used with `reduce`. Well, if you want to solve this problem it can't, it does evaluate just fine to a solution to a different problem. ;-)
Michał Marczyk
"can't be used with reduce. " s/reduce/apply. :) can be used with reduce, cant be used with apply because it has a fixed number of args.
Arthur Ulfeldt
I see that I've messed up my final two sentences above... I meant to say that (1) you've got to be careful when using this to solve the original problem with `reduce` and not supply an initial value for the accumulator; (2) you can't use it to solve the generalised versions of the problem. That's because it's going to keep squaring the accumulator and thus solve an entirely different numeric problem. Thanks for making me correct myself. :-) Also, `apply` works just fine with fixed arity functions, provided of course that the correct number of arguments is supplied.
Michał Marczyk
I had not though of that! yes using sum-of-squares with reduce will not work at all.
Arthur Ulfeldt
You could use `#(+ %1 (* %2 %2))` with an initial accumulator value of 0, though. BTW, I've taken a shot at an answer to your comment on the question -- how'd you like it? :-)
Michał Marczyk
+7  A: 

; why only 3? how about N

(defn sum-of-squares [& nums]  
  (reduce + (map #(* % %) (drop 1 (sort nums)))))

or if you want "the sum of the greatest two numbers:

(defn sum-of-squares [& nums]  
  (reduce + (map #(* % %) (take 2 (reverse (sort nums))))))

(take 2 (reverse (sort nums))) fromMichał Marczyk's answer.

Arthur Ulfeldt
I generally prefer reduce to apply because it saves bulding a huge function call and can preserve lazy evaluation (though in this case the (sort breaks the lazy)
Arthur Ulfeldt
Michał Marczyk
There might be differences in apply and reduce. Consider `(reduce str some-strings)` and `(apply str some-strings)`. The latter is better because it uses a StringBuilder internally. Things like `+` are optimised in the two-arg case. I'm not sure whether the optimisiations apply with `reduce`, but it may make a difference here.
kotarak
+7  A: 
(defn foo [& xs]
  (let [big-xs (take 2 (sort-by - xs))]
    (reduce + (map * big-xs big-xs))))
Brian Carper
Oh, that's cool... Makes the `(reverse (sort xs))` look a bit verbose. I've only just re-discovered `sort-by` (for use in solution to an alternate version of the problem stated in my answer) and again found that it's not quite like Haskell's `sortBy`... which I'm rather more used to. I've been mumbling curses about this for a minute, then noticed this -- and it got the point across. +1 for that.
Michał Marczyk