我得到了两个类似下面的2d数组,我想将它们组合起来
a b combine(a,b) combine(b,a)
1 1 1 3 3 1 1 1 3 3 3 3 1 1 1
2 2 2 4 4 2 2 2 4 4 4 4 2 2 2
5 5 0 0 0 5 5 5 5 0 0 0
我正在尝试下面这样的东西,但我对此感到困惑
import java.util.Arrays;
class Main {
public static int[] [] combine(int[][] a, int[][] b) {
System.out.println(a[0].length+b[0].length);
int[][] c = new int[a[0].length+b[0].length][b[1].length];
for(int i = 0; i < a[0].length+b[0].length; i++) {
for (int j = 0; j < b[1].length; j++) {
System.out.println("a "+a[i][j]);
if(i>a[0].length)
{
c[i][j]=b[i][j]
}
}
}
return c;
}
public static void main(String[] args) {
int[][] a = new int[][] {{1,1,1}, {2,2, 2}};
int[][] b = new int[][] {{3,3}, {4, 4},{5,5}};
combine( a, b);
/*
System.out.println(Arrays.deepToString(combine( a, b))
.replace("],","n").replace(",","t| ")
.replaceAll("[\[\]]", " "));
*/
}
}
如有任何帮助,我们将不胜感激。谢谢
尝试分解问题:
首先计算出新阵列的尺寸。假设两个输入数组都是矩形的(不是锯齿状的(,组合数组的行数将与输入数组中具有更多行的行数一样多,并且列数将与输出数组的列数之和一样多。因此,
int[][] c = new int[Math.max(a.length, b.length)][a[0].length + b[0].length];
然后,可以像正常情况一样将第一个输入数组填充到c
中:
for(int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
c[i][j] = a[i][j];
}
}
第二个输入数组需要偏移几位。到底有多少地方?第一个输入数组中的列数:
for (int i = 0 ; i < b.length ; i++) {
for (int j = 0 ; j < b[0].length ; j++) {
c[i][j + a[0].length] = b[i][j];
// ^^^^^^^^^^^^^
}
}
就这样!
public static int[] [] combine(int[][] a, int[][] b) {
System.out.println(a[0].length+b[0].length);
int[][] c = new int[Math.max(a.length, b.length)][a[0].length + b[0].length];
for(int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
c[i][j] = a[i][j];
}
}
for (int i = 0 ; i < b.length ; i++) {
for (int j = 0 ; j < b[0].length ; j++) {
c[i][j + a[0].length] = b[i][j];
}
}
return c;
}
最好计算结果数组的大小,然后分别用a
和b
的值填充:
public static int[] [] combine(int[][] a, int[][] b) {
int cols = a[0].length+b[0].length;
int rows = Math.max(a.length, b.length);
System.out.println("Result: rows=" + rows + ", columns=" + cols);
int[][] c = new int[rows][cols];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
c[i][j] = a[i][j];
}
}
for (int i = 0; i < b.length; i++) {
for (int j = a[0].length; j < cols; j++) { column index in the result shifted
c[i][j] = b[i][j - a[0].length];
}
}
for (int[] row : c) {
System.out.println(Arrays.toString(row));
}
return c;
}
测试:
int[][] a = new int[][] {{1,1,1}, {2,2,2}};
int[][] b = new int[][] {{3,3}, {4,4}, {5,5}};
combine(a, b);
combine(b, a);
输出:
Result: rows=3, columns=5
[1, 1, 1, 3, 3]
[2, 2, 2, 4, 4]
[0, 0, 0, 5, 5]
Result: rows=3, columns=5
[3, 3, 1, 1, 1]
[4, 4, 2, 2, 2]
[5, 5, 0, 0, 0]