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.
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];
}
(defn compute-contrib [daily-values total-values](loop [contrib []daily-values daily-valuestotal-values total-values](if (empty? daily-values)contrib(recur (conj contrib (* (first daily-values) (reduce (fn [sum total-value] (* sum (+ (/ total-value 100.0) 1.0)))1.0(rest total-values))))(rest daily-values)(rest total-values)))) )
Oops.
--
Protege: What is this seething mass of parentheses?!
Master: Your father's Lisp REPL. This is the language of a true
hacker. Not as clumsy or random as C++; a language for a more
civilized age.
David - you are right the variable should be called product not sum. This is just some poorly written Java code that I am translating to Clojure.
Justin - thanks for the idea on how to visualize such algorithms and the picture you shared.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@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+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
I really liked the way you kept refactoring the original solution by Huahai to make it more and more logical and elegant. I verified that each refactored function produced the correct results.
Thanks for sharing your valuable thoughts and techniques.
Shoeb
-----Original Message-----
From: clo...@googlegroups.com [mailto:clo...@googlegroups.com] On Behalf Of Huahai Yang
Sent: Thursday, June 30, 2011 12:33 AM
To: Clojure
Subject: Re: Translating Java code with nested for loops
--