Here's one way.

(defn tails [coll]
  (take-while seq (iterate rest coll)))

(defn calc [total-values daily-values]
  (map * daily-values (for [tail (tails total-values)]
                        (reduce #(* %1 (inc (/ %2 100.0)))
                                1.0
                                (rest tail)))))

In translating it, I first tried to visualize the algorithm[1]. Then I
transcribed that visualization into the usual suspects: map/for,
reduce, filter. Having a solid grasp of each of those -- not to
mention the rest of clojure.core -- is very helpful.

[1] http://i.imgur.com/XDZhm.png (crude drawing of the first step)

Hope that helps,

Justin

On Jun 28, 8:20 pm, "Bhinderwala, Shoeb"
<sabhinderw...@wellington.com> wrote:
> Hi
>
> I have been learning clojure for some time but am a bit stumped when
> translating code with nested for loops.
>
> Can someone help me to translate the following java code to clojure
> elegantly:
>
> The inputs are two arrays of type double of the same length -
> dailyValues and totalValues. The output is the array contrib of the same
> length.
>
>         int n = dailyValues.length;
>
>         for (int i = 0; i < n; i++)
>         {
>             sum = 1.0;
>             for (int j = i + 1; j < n; j++)
>             {
>                 sum *= (1.0 + (totalValues[j] / 100.0));
>             }
>
>             contrib[i] = sum * dailyValues[i];
>         }
>
> Many thanks for your help.
>
> -- Shoeb

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to