Reputation: 260
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,
Upvotes: 0
Views: 856
Reputation: 126
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)
So add the following function to your code:
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)
Upvotes: 1
Reputation: 51553
First, you should sum integers rather than doubles. You can convert the integers to doubles if necessary.
Second, you need to include a stop condition. I suggest a total length. This would make the method signature:
public int[] sequenceSum(int[] sequence, int length)
Rather than give you code, I'll just give you the steps you need to write the code:
Create the int output array of length length.
Get the sequence length.
Copy the sequence array to the output array.
Sum the sequence values, from index 0 to index sequence length - 1, and add the sum to the output array.
Repeat step 4, adding 1 to the start index and adding 1 to the end index, until the output array is full.
Upvotes: 1