问题描述
我正在尝试将两个不同大小的矩阵相加。例如,结果矩阵应该是 matOne[0][0]+matTwo[0][0];但是,我无法考虑它们的不同大小(如果存在缺失值,则应假定它为 0)。 这是我的代码:
int[][] go(int[][] matOne,int[][] matTwo)
{
int size= Math.max(matOne.length,matTwo.length);
int[][] matThree= new int [size][];
int c;
for (int i=0; i<size; i++) {
c= Math.max(matOne[i].length,matTwo[i].length);
for (int j = 0; j < c; j++) {
if (matOne[j].length > i) {
matThree[i][j] += matOne[i][j];
}
if (matTwo[j].length > i) {
matThree[i][j] += matTwo[i][j];
}
}
}
return matOne;
}
解决方法
我在代码中看到以下错误:
-
你从不分配内部数组。获得
size
后,您正确地创建了外部数组。获得c
后,您忘记为该行创建内部数组。 -
就在
i
循环内部,matOne[i]
和matTwo[i]
之一很可能最终失败,以较短者为准。 -
变量
i
迭代行,变量j
迭代一行中的列,这意味着[i][j]
语句中的+=
是正确的,但是matOne[j].length > i
应该是matOne[i].length > j
。matTwo
也一样。 -
你返回了错误的数组。
这是固定代码,使用更好的变量名:
static int[][] go(int[][] matOne,int[][] matTwo) {
int rows = Math.max(matOne.length,matTwo.length);
int[][] matThree = new int [rows][];
for (int r = 0; r < rows; r++) {
int cells = Math.max((matOne.length > r ? matOne[r].length : 0),(matTwo.length > r ? matTwo[r].length : 0));
matThree[r] = new int[cells];
for (int c = 0; c < cells; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
测试
public static void main(String[] args) {
int[][] matOne = { { 1,2,3 },{ 4,5,6 } };
int[][] matTwo = { { 7,8 },{ 9,10 },{ 11,12 } };
int[][] matThree = go(matOne,matTwo);
print(matOne);
System.out.println("+");
print(matTwo);
System.out.println("=");
print(matThree);
}
static void print(int[][] mat) {
for (int[] row : mat) {
for (int cell : row)
System.out.printf(" %2d",cell);
System.out.println();
}
}
输出
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12
如果你不希望结果是一个锯齿状的数组,即你希望结果是一个二维矩形矩阵,请按如下方式更改代码:
static int[][] go(int[][] matOne,matTwo.length);
int cols = 0;
for (int[] row : matOne)
cols = Math.max(cols,row.length);
for (int[] row : matTwo)
cols = Math.max(cols,row.length);
int[][] matThree = new int [rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (matOne.length > r && matOne[r].length > c) {
matThree[r][c] += matOne[r][c];
}
if (matTwo.length > r && matTwo[r].length > c) {
matThree[r][c] += matTwo[r][c];
}
}
}
return matThree;
}
输出
1 2 3
4 5 6
+
7 8
9 10
11 12
=
8 10 3
13 15 6
11 12 0
,
就在内循环之前;替换 'c' 的当前计算并为 matThree 分配一行。
c = 0;
if (i < matOne.length)
c = matOne[i].length;
if (i < matTwo.length && matTwo[i].length > c)
c = matTwo[i].length;
matThree[i] = new int[c];
内循环内的代码应该是:
int elem1 = 0,elem2 = 0;
if (i < matOne.length && j < matOne[i].length)
elem1 = matOne[i][j];
if (i < matTwo.length && j < matTwo[i].length)
elem2 = matTwo[i][j];
matThree[i][j] = elem1 + elem2;
首先需要为matThree的当前行分配存储空间。
其次,您需要检查行和列是否都在每个矩阵的范围内。根据我的口味,最清楚的是显式提取值,默认为零,即变量 elem1 和 elem2。