java - 将 2 个不同大小的二维数组加在一起
问题描述
我正在尝试将两个不同大小的矩阵相加。例如,结果矩阵应该是 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, int[][] matTwo) {
int rows = Math.max(matOne.length, 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
推荐阅读
- ios - 向 Xcode 10 Core Data 生成的文件添加方法
- c# - SQLiteOpenHelper - 无法访问已处置的对象
- php - 如何在php中完全解码base64字符串?
- c# - 尝试根据属性类型从 DataTable 中删除特定列
- c++ - 用于保存任何维度数组的 C++ 变量
- user-interface - 有没有使用 Solidity 创建 GUI 的选项?
- reactjs - onChange 中的多个函数?我看到的答案不起作用
- data-structures - 使用堆栈将中缀转换为后缀表达式时该怎么办?
- javascript - 如何导航到另一个页面而不在 NextJs 中重新加载整个页面?
- selenium - 是否可以使用 Selenium 关闭在不同会话中打开的所有浏览器?