[英]how to combine two 2d arrays horizontally in java withdifferent dimensions
我得到了如下所示的 2 2d arrays,我想將它們組合起來
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("[\\[\\]]", " "));
*/
}
}
任何幫助將不勝感激。謝謝
嘗試分解問題:
首先計算出新數組的維度。 假設兩個輸入 arrays 都是矩形(不是鋸齒狀),組合數組的行數將與輸入數組中行數更多的那個一樣多,列數將與輸入 arrays 的列數之和一樣多。 所以,
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);
Output:
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.