Horizontally combine two 2D arrays in java -
i trying combine 2 2d arrays a, b horizontally such if:
a = [[1, 1], [1, 1]] b = [[2, 2], [2, 2]]
then merged array c should like:
c = [[1, 1, 2, 2], [1, 1, 2, 2]]
it simple vertically combine this:
d = [[1, 1], [1, 1], [2, 2], [2, 2]]
but want horizontally combine them. idea on how accomplish 2 2d arrays have same dimension?
if dimensions of arrays , b same (i.e. positive integers x , y):
int[][] = new int[x][y]; int[][] b = new int[x][x];
then create new array as:
int[][] c = new int[2*x][y];
and use nested loops fill-in corresponding elements:
public class main { public static void main(string[] args) { int[][] = {{1,1},{1,1}}; int[][] b = {{2,2},{2,2}}; int[][] c = new int[2*a.length][a.length]; for(int = 0; < 2*a.length; i++) { (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]; } } } } }
Comments
Post a Comment