Kokolo - 1 year ago 83
Java Question

# How to sum up N array elements, to the left of the given element?

Sorry if the question is confusing, I am new to programming and I didn't know how to formulate it, and even Google couldn't understand me number of times.

I am trying to solve some kind of Fibonnaci sequence, but instead of summing the last 2 numbers, it should sum up the last N numbers.

``````public double[] sequenceSum(double[] sequence) {
//some fancy method here
}
``````

Where the sequence.length is actually how much numbers you should sum up.
So if the call is:
seqeunceSum(1,2,3,4);

...the sequence should continue {1,2,3,4,10,18,35,67...}.

if the call is:
seqeunceSum(1,0,1,0,1);
...the sequence should continue {1,0,1,0,1,3,5,10,19,38....}.

The sequence has its limits, of course, otherwise it'd be infinite, but I only need help with how to sum up N number of array elements, to the left

Thanks a lot,

EDIT:

Thanks, I took few opinions from here and I solved it.

And yes, the sequence has limits, sorry for not including that in the parameters, I judged on previous advise to ask Minimal and Specific questions.

Here is my code:

``````public double[] sequenceSum(double[] sequence, int n) {
double[] xArray = Arrays.copyOf(sequence, n);
for(int i = sequence.length; i<n; i++){
double sum = 0;
for (int j=(i-sequence.length); j < i; j++) {
sum += xArray[j];
}
xArray[i] = sum;
}
return xArray;
}
}
``````

Thanks everyone,

A best practice is to keep same functionality that could be reused in a own/separate function, so you can use this anywhere else in your programm. (Also it makes your code more structured and readable)

``````public double sumAll(double[] numbers) {
double result = 0;
for(int i = 0 ; i < numbers.length; i++){
result += numbers[i];
}

return result;
}
``````

And than you can call it inside your sequenceSum function like:

``````double sum = sumAll(sequence);
// Your code to create the next sequence elements...
``````

Another hint: If you just use this function for the Fibbonaci sequence and similar integer problems use the data type int, because floating point numbers (in this case double) add up floating point "noise". (You find informations about this problem here)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download