![](/img/trans.png)
[英]how to combine two 2d arrays horizontally in java withdifferent dimensions
[英]Horizontally combine two 2D arrays in java
我試圖將兩個二維數組 a, b 水平組合,如果:
a = [[1, 1],
[1, 1]]
b = [[2, 2],
[2, 2]]
那么合並后的數組 c 應該如下所示:
c = [[1, 1, 2, 2],
[1, 1, 2, 2]]
垂直組合非常簡單,然后看起來像這樣:
d = [[1, 1],
[1, 1],
[2, 2],
[2, 2]]
但我想水平組合它們。 關於如何為具有相同維度的兩個二維數組完成此操作的任何想法?
如果數組 a 和 b 的維數相同(即對於某些正整數 x 和 y):
int[][] a = new int[x][y];
int[][] b = new int[x][x];
然后創建一個新數組:
int[][] c = new int[2*x][y];
並使用嵌套的 for 循環來填充相應的元素:
public class Main {
public static void main(String[] args) {
int[][] a = {{1,1},{1,1}};
int[][] b = {{2,2},{2,2}};
int[][] c = new int[2*a.length][a.length];
for(int i = 0; i < 2*a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (i < a.length) {
c[i][j] = a[i][j];
} else {
c[i][j] = b[i - a.length][j];
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.