我很难想出一种在二维数组中找到相邻值之和的好方法。我需要在索引位置找到所有相邻值的总和。如果位置是边缘,我需要将它的值转换为总和。因此,每个元素将有 4 个值对其总和做出贡献。
例子。
索引 [0][0] = 5.0 处的元素。[0][1] = 2, [1][0] = 4. index[0][0] = 5(左/自身镜像) + 5(上/自身镜像) + 2(右边)+ 4(下面)= 16。
到目前为止,我的代码如下。更好的方法的建议将不胜感激。此代码正在获取
ArrayOutOfBounds:3
在评论之后的行上说 //ERROR**
Public static double [][] getSumWeight(double [][] map){
int base = 0;
//int count = getEnhancementLevel();
int row = map.length;
int col = map[0].length;
int newRow = row*2;
int newCol = col*2;
double [] [] sumMap = new double [row][col];
double [][] weightMap = new double [newRow][newCol];
//getting the corner sum weights
for (int i = 0; i < map.length; i++){
for (int j = 0; j < map[i].length; j++){
if (i == 0 && j == 0){
double result = 0;
result += (map[0][0])*2;
result += map[0][1];
result += map[1][0];
sumMap[0][0] = result;
System.out.println("corner" + sumMap[0][0]);
}
else if (i == 0 && j == map[0].length){
double result = 0;
result += map[0][map[0].length];
result += map[0][map[0].length-1];
result += map[1][map[0].length];
sumMap[i][j] = result;
}else if (i == map.length && j == 0){
}else if (i == map.length && j == map[map.length].length){
}
//getting the mid(s) of the top row
else if (i == 0 && j != 0 && j != map[0].length){
double result = 0;
result += map[i][j]; //top value or mirror
result += map[i][j-1]; // left value
//ERROR****
result += map[i][j+1]; // right value
result += map[i+1][j]; // bottom value
sumMap[i][j] = result;
}
//getting the mid(s) of the bottom row
else if (i == map.length && j != 0 && j != map[map.length].length){
double result = 0;
result += map[i][j];
result += map[i][j-1];
result += map[i][j+1];
result += map[i-1][j];
sumMap[i][j] = result;
}
//getting the mid(s) of the left most column
else if (j == 0 && i != 0 && i != map.length){
double result = 0;
result += map[i][j];
result += map[i-1][j];
result += map[i+1][j];
result += map[i][j+1];
sumMap[i][j] = result;
}
//getting the mid(s) of the right most column
else if (j == map[0].length && i != 0 && i != map.length){
double result = 0;
result += map[i][j];
result += map[i-1][j];
result += map[i+1][j];
result += map[i][j-1];
sumMap[i][j] = result;
}
//filling in all the remaining values
else{
double result = 0;
result += map[i-1][j];
result += map[i+1][j];
result += map[i][j-1];
result += map[i][j+1];
sumMap[i][j] = result;
}
}
}
for (int i = 0; i < map.length; i++){
for (int j = 0; j < map[i].length; j++){
System.out.println(sumMap[i][j]);
}}
return sumMap;
}