Suppose that I have an array consisting of n elements.
1 2 3 4 5 6 ... n
I need to find a way to extract the sums of consecutive elements in this array using C++. Like this:
1, 2, 3,...n, 1+2, 2+3, 3+4,...(n-1)+n, 1+2+3, 2+3+4,...(n-2)+(n-1)+n,...1+2+3...n
So far I figured out I need to iterate through this array by summing certain number of elements on each run. I am not sure if it is possible to implement the algorithm I explained above. There might be a better solution but this is the best I could come up with.
How this. Given an array of 5 integers : 5, 7, 3, 9, 4
This produces the following results...
I hope this helps...
Let's inspect case with 4 elements:
As you can see every part for N sum array is of size lower from original array by (N-1). So you need target array of size: N + (N-1) + (N-2) + ... 1 - which is N*(1+N)/2
See test on ideone
See it working at ideone.com:
This should use the previously calculated sums too.
You can use
std::transform
to do this:Of course you don't have to use an ostream_iterator as it's output, you can also use another containers iterator, or a
std::back_inserter
for a container or any otherOutputIterator
references
http://en.cppreference.com/w/cpp/algorithm/transform
http://en.cppreference.com/w/cpp/utility/functional/plus
http://en.cppreference.com/w/cpp/container/vector
EDIT:
Let's call the original array A.
Let's call the array of sums of k consecutive elements B.
Let's call the array of sums of k+1 consecutive elements C.
Each of the array is of size n.
First k-2 cells of C are irrelevant.
Iterate the above code for each k up to n and after each pass concatenate the resulting array to the result from previous iteration. (Make sure to check the corner cases well)
I think this code should do what you are asking for: