Home > Back-end >  How can I add every element with the second and 3rd element after it in a grid (2D array)?
How can I add every element with the second and 3rd element after it in a grid (2D array)?

Time:11-14

I have a 2D array and I'm trying to add element x to the two next elements in the grid horizontally while not going out of bounds.

For instance,

if this is my grid,

[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

I want an output array that looks like

[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

because every element is added with the next 2 elements after it.

Here had been my attempt so far:

        int n = 2;
        for (int x = 0; x < array.length; x   ) {
            for (int y = 0; y < array.length; y  ){
                for(int j = x 1; j <= x   n && j < array.length; j   ){
                l.add(array[x][y]   array[x   j][y]);
            }

However, when I try to run this, I get an index out of bound exception. I've tried to change the parameters of each variable but to no avail. What should I change in this?

CodePudding user response:

You could iterate the array and add the current value with the next two values if the current index is not the last index.

Assuming you have a 2D array of ints called "grid", you could do something like this:

int[][] newGrid = new int[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i  ) {
    for (int j = 0; j < grid[0].length; j  ) {
        if (j < grid[0].length - 2) {
            newGrid[i][j] = grid[i][j]   grid[i][j   1]   grid[i][j   2];
        } else {
            newGrid[i][j] = grid[i][j];
        }
    }
}
  • Related