总和在一个数组,C的连续元素++ [英] Sum of consecutive elements in an array, C++
问题描述
假设我有包括n个元素的数组。
Suppose that I have an array consisting of n elements.
1 2 3 4 5 6 ... n
我需要找到一个方法来提取使用C ++这个数组的连续元素的总和。 像这样的:
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.
推荐答案
让我们检查的情况下有4个元素:
Let's inspect case with 4 elements:
{1,3,4,5, // from original array
4,7,9, // sum of 2 consecutive elements
8,12, // sum of 3
13} // sum of 4
正如你所看到的每一个部分对于N之和数组的大小较低由原来的数组(N-1)。因此,你需要目标大小的数组:N +(N-1)+(N-2)+ ... 1 - 这是N *(1 + N)/ 2
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
int* createSumArray(int* arr, int size)
{
int ti = 0; // target index
int* ta = new int[size*(size+1)/2];
for (int s = 1; s <= size; ++s) // how many elements to sum
{
for (int si = 0; si < size + 1 - s; ++si)
{
ta[ti] = 0;
for (int i = si; i < si + s; ++i)
ta[ti] += arr[i];
++ti;
}
}
return ta;
}
请参阅测试在 ideone
这篇关于总和在一个数组,C的连续元素++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!