我有一个大的2D矩阵A2D,列等级和行等级总是相等,并且均匀地除以4.我想将列等级和行等级减少到它们各自的四分之一(1/4)形成另一个矩阵B2D。每个B2D元素是A2D的4×4子矩阵的平均值。为了清楚地说明我想要做什么,我以一个简单的8x8矩阵为例,并提供以下代码片段供您参考。我的解决方案非常笨拙。你能告诉我另一个性能更好的解决方案吗?提前谢谢。
int arr[8][8] =
{
{11, 12, 13, 14, 15, 16, 17, 18},
{21, 22, 23, 24, 25, 26, 27, 28},
{31, 32, 33, 34, 35, 36, 37, 38},
{41, 42, 43, 44, 45, 46, 47, 48},
{51, 52, 53, 54, 55, 56, 57, 58},
{61, 62, 63, 64, 65, 66, 67, 68},
{71, 72, 73, 74, 75, 76, 77, 78},
{81, 82, 83, 84, 85, 86, 87, 88}
};
int** pColAvg = new int* [8];
for (int i = 0; i < 8; i++)
pColAvg[i] = new int[2];
for (int nRow = 0; nRow < 8; nRow + 4)
{
for (int nCol = 0; nCol < 8; nCol + 4)
{
int Avg = 0;
Avg += arr[nRow][nCol];
Avg += arr[nRow][nCol + 1];
Avg += arr[nRow][nCol + 2];
Avg += arr[nRow][nCol + 3];
Avg /= 4;
pColAvg[nRow][nCol/4] = Avg;
}
}
int** pAvgArray = new int* [2];
for (int i = 0; i < 2; i++)
pAvgArray[i] = new int[2];
for (int nRow = 0; nRow < 8; nRow + 4)
{
for (int nCol = 0; nCol < 2; nCol++)
{
int Avg = 0;
Avg += pColAvg[nRow][nCol];
Avg += pColAvg[nRow + 1][nCol];
Avg += pColAvg[nRow + 2][nCol];
Avg += pColAvg[nRow + 3][nCol];
Avg /= 4;
pAvgArray[nRow/4][nCol] = Avg;
}
}
for (int i = 0; i < 8; i++)
delete [] pColAvg[i];
delete [] pColAvg;
for (int i = 0; i < 2; i++)
delete [] pAvgArray[i];
delete [] pAvgArray;
答案 0 :(得分:2)
我认为您的解决方案可能不正确(即使您的平均值是指平均值的平均值)。这是我的解决方案:
int** solveIt(int **arr, int n){
int **result = new int*[n/4];
for(int i=0; i<n; i+=4){
result[i] = new int[n/4];
for(int j=0; j<n; j+=4){
int sum = 0;
for(int k=0; k<4; k++)
for(int q=0; q<4; q++)
sum += arr[i+k][j+q];
result[i/4][j/4] = sum/16;
}
}
return result;
}
这是获取该数组的数组和大小的函数,并返回结果数组。
编辑: 以及解决方案不起作用的示例:
1 1 1 1
1 1 1 2
1 1 1 1
1 1 0 1
答案是:
1
但你的解决方案会给出:
0