0

I'm confused on how to make a java method to append two different 2D arrays without using/importing the arrays class. This is what I have so far:

private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
    Cell[][] third = new Cell[first.length][first[0].length + second[0].length];

    for (int i = 0; i < first.length; i++) {
        for (int j = 0; j < first[i].length; j++) {
            third[i][j] = first[i][j];
        }
    }
    for (int i = 0; i < second.length; i++) {
        for (int j = 0; j < second[i].length; j++) {
            // don't know what to do here
        }
    }
    return third;
}

A Cell is just an object, but I'm trying to understand the logic behind appending arrays so any help would be appreciated!

Also, I know there is a similar question found here (How do you append two 2D array in java properly?), but the answer is given on appending arrays from the top down (given both parameter arrays have the same amount of columns), while I am looking for appending arrays from side to side (assuming both parameter arrays have the same amount of rows).

Community
  • 1
  • 1
derpt34
  • 39
  • 5
  • ```third[i][first[0].length + j] = second[i][j];``` –  Nov 29 '15 at 01:37
  • Something like `third[ first.length + i ][ first[0].length + j ] = second[i][j]`? You also assume that `first[X].length` is the same for all `X` (and the same for `second[X]`). – Kenney Nov 29 '15 at 01:39

1 Answers1

0

You're almost there. I think something like this is what you're looking for.

private Cell[][] appendArrays(Cell[][] first, Cell[][] second) {
    Cell[][] third = new Cell[first.length][first[0].length + second[0].length];

    for (int i = 0; i < first.length; i++) {
        for (int j = 0; j < first[i].length; j++) {
            third[i][j] = first[i][j];
        }
        for (int j = first[i].length; j < first[i].length + second[i].length; j++) {
            third[i][j] = second[i][j-first[i].length];
        }
    }
    return third;
}
Rania
  • 18
  • 2
Ken Slade
  • 343
  • 2
  • 8