我有4x4 2D数组,每个索引中都有值。我想要一个函数来计算数组的行/列的总和,并将其存储在第一个/最后一列,并让其他索引恢复为0.
这就是我必须渲染我的数组:
public static void print2Darray(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
System.out.print(numbers[i][j]);
System.out.print("\t");
}
System.out.println();
}
}
显示如下内容:
10 15 30 40
15 5 8 2
20 2 4 2
1 4 5 0
目前这是我的功能:
public static void sumLeft(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i][0] = (numbers[i][0] + numbers[i][1] + numbers[i][2] + numbers[i][3]);
if (i == 3) {
numbers[0][1] = 0;
numbers[0][2] = 0;
numbers[0][3] = 0;
numbers[1][1] = 0;
numbers[1][2] = 0;
numbers[1][3] = 0;
numbers[2][1] = 0;
numbers[2][2] = 0;
numbers[2][3] = 0;
numbers[3][1] = 0;
numbers[3][2] = 0;
numbers[3][3] = 0;
}
}
}
这是做什么的:
95 0 0 0
30 0 0 0
28 0 0 0
10 0 0 0
我只是想找到一种能够在没有&#34;作弊的情况下做到这一点的算法。或者只是黑客攻击它。
答案 0 :(得分:3)
您需要做的就是遍历“row”数组的元素:
public static void sumLeft(int[][] numbers) {
for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < numbers[i].length; j++) {
numbers[i][0] += numbers[i][j];
numbers[i][j] = 0;
}
}
}
答案 1 :(得分:2)
以相反的顺序使用内部循环:
for (int i = 0; i < numbers.length; i++) { // for all rows
int sum = 0; // about to be sum, reset every row
for (int j = numbers[i].length -1 ; j >=0; j--) { // iterate reverse in columns
if (j == 0) {
numbers[i][j] += sum; // final sum
} else {
sum += numbers[i][j]; // keep evaluating
numbers[i][j] = 0; //reset
}
}
}
答案 2 :(得分:2)
你为什么不这样做:
for (int i = 0; i < numbers.length; i++) {
for (int j = 1; j < numbers[i].length; j++) {
numbers[i][0] += numbers[i][j];
numbers[i][j] = 0;
}
}