有效地计算多维数组的累积和?

Efficiently calculate cumulative sum of a multidimensional array?

本文关键字:数组 计算 有效地      更新时间:2023-10-16

如果我有一个一维数组 arr[x]

cumulative_arr[x]=cumulative_arr[x-1]+arr[x]

对于 2D 数组 arr[x][y]

cumulative_arr[x][y]=cumulative_arr[x-1][y]+cumulative_arr[x][y-1]-cumulative_arr[x-1][y-1]+arr[x][y]

如何为较大维度的数组横向扩展此方法?

4D 数组的累积总和为:-

cumulative_sum[w][x][y][z] = sum of arr[i][j][k][l] for all i<=w,j<=x,k<=y and l<=z.

我想找到一个 N 维数组的方法。

既然你标记为C++,我们开始...

一维:

static const unsigned int ARRAY_CAPACITY = 64u;
int sum = 0;
sum = std::accumulate(&array[0], &array[ARRAY_CAPACITY], 0);

二维:

static const unsigned int MAXIMUM_ROWS = 32u;
static const unsigned int MAXIMUM_COLUMNS = 16u;
int sum = 0;
sum = std::accumulate(&array[0][0], &array[MAXIMUM_ROWS][MAXIMUM_COLUMNS], 0);

三维(说明经典for循环(:

int sum = 0;
for (int x = 0; x < CAPACITY_DIMENSION_3; ++x)
{
for (int y = 0; y < CAPACITY_DIMENSION_2; ++y)
{
for (int z = 0; z < CAPACITY_DIMENSION_1; ++z)
{
sum += array[x][y][z];
}
}
}

如果数组插槽对于所有维度都是连续的,则可以将数组强制转换为单个维度,并汇总为单个维度数组。

你可以创建一个递归函数,如下所示:

function dimensionalSum(arr: any[]){
if(typeof arr[0] == 'number'){
return arr.reduce((acc, num) => acc + num, 0);
}
return arr.reduce((acc, dim) => acc + dimensionalSum(dim), 0);
}

注意:该示例是用打字稿编写的,它只是一个概念证明。

这样,您有多少个维度都无关紧要。

如果你所需要的只是一种计算任意N维数组所有维度的累积和数组的方法,那么,在Python中,你可以利用NumPycumsum()的强大功能:

import numpy as np

def cumsum_all(arr):
result = arr
for i in range(arr.ndim):
result = np.cumsum(result, i)
return result

测试这个会得到:

arr = np.arange((2 * 3)).reshape((2, 3))
print(arr)
# [[0 1 2]
#  [3 4 5]]
print(cumsum_all(arr))
# [[ 0  1  3]
#  [ 3  8 15]]
arr = np.arange((2 * 3 * 4)).reshape((2, 3, 4))
print(arr)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]
print(cumsum_all(arr))
# [[[  0   1   3   6]
#   [  4  10  18  28]
#   [ 12  27  45  66]]
#  [[ 12  26  42  60]
#   [ 32  68 108 152]
#   [ 60 126 198 276]]]