James McDowell
James McDowell

Reputation: 2768

What is the best way to concatenate multi-dimensional arrays in java?

I have 2 dimensional, 3 dimensional and 4 dimensional arrays. (All at different times)
If I want to concatenate 4 2D arrays (4 2x2's in to 1 4x4), I can do this with simple looping

int[][] result = new int[2 * array1.length][2 * array1.length];
for(int x = 0; x < array1.length; x++)
    for(int y = 0; y < array1.length; y++)
        result[x][y] = array1[x][y];
for(int x = array1.length; x < result.length; x++)
   for(int y = 0; y < array1.length; y++)
       result[x][y] = array2[x - array1.length][y];
...

As you can see, this gets very messy (2^n sets of loops where n is number of dimensions). I know I could simplify this with System.arraycopy, but I would still need just as many sets of loops.
Is there an easier way for me to do this? Preferrably one that works for all dimensional arrays?
Note that I am adding on to each dimension, not just adding one to the end of another. To visualize what I'm doing, imagine each 2D array as a square and each 3D array as a cube. To combine them, stitch them together forming a 2x2 square (where each unit is one 2D array) or a 2x2x2 cube (where each unit is one 3D array).
Here's a poorly drawn visualization of 2D combination.
|--| + |--| + |--| + |--| = |--|--|
|--| |--| |--| |--| |--|--|
. |--|--|

Upvotes: 2

Views: 1678

Answers (1)

Anonymous
Anonymous

Reputation: 86306

For 2-dimensional arrays you can declare:

private static void fillInto(int[][] biggerArray, int[][] smallArray, int targetI, int targetJ) {
    int expectedLength = smallArray.length;
    for (int i = 0; i < smallArray.length; i++) {
        if (smallArray[i].length != expectedLength) {
            throw new IllegalArgumentException("Unexpected length " + smallArray[i].length);
        }
        System.arraycopy(smallArray[i], 0, biggerArray[targetI + i], targetJ, expectedLength);
    }
}

Now you can go:

    int[][] array1 = new int[][] { { 1, 2 }, { 3, 2 } }; 
    int[][] array2 = new int[][] { { 3, 4 }, { 6, 4 } }; 
    int[][] array3 = new int[][] { { 5, 5 }, { 10, 6 } }; 
    int[][] array4 = new int[][] { { 7, 6 }, { 13, 8 } };

    int[][] result = new int[2 * array1.length][2 * array1.length];
    fillInto(result, array1, 0, 0);
    fillInto(result, array2, array1.length, 0);
    fillInto(result, array3, 0, array1.length);
    fillInto(result, array4, array1.length, array1.length);
    System.out.println(Arrays.deepToString(result));

Result:

[[1, 2, 5, 5], [3, 2, 10, 6], [3, 4, 7, 6], [6, 4, 13, 8]]

You can probably do something similar for 3 and 4 dimensions.

Upvotes: 1

Related Questions