Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Iterate over a 2-dimensional array starting with the middle

Tags:

java

arrays

I have this totally normal loop over a 2 dimensional array.

for(int i = 0; i<array.length; i++){
    for(int j = 0; i<array.length; j++){
        array[i][j].doSomething();
    }
}

I want to go through this 2 dimensional array, starting in the middle. For example, if the array has a length of 100 for both dimensions, I want it to go over it like this:

array[50][50] //middle of array
array[49][50] //x-1
array[50][49] //y-1
array[51][50] //x+1
array[50][51] //y+1
array[48][50] //x-2
array[49][49] //x-1 and y-1
array[50][48] //y-2
array[51][49] //x+1 and y-1
array[52][50] //x+2
array[51][51] //x+1 and y+1
array[50][52] //y+2
array[49][51] //x-1 and y+1
etc.

I've been spending hours on finding an efficient way and finding a solution on the internet, but I haven't found a great answer yet. Anyone who knows how to do this?

like image 310
Simon Baars Avatar asked Oct 27 '25 14:10

Simon Baars


1 Answers

This will not yet give you any java code but rather an idea on how to approach the problem.

Draw the grid of your array of a far smaller size on a pice of paper and draw the numbers in which the cell should get reached in each cell.

[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][1][ ][ ]
[ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ]
[ ][ ][3][ ][ ]
[ ][2][1][4][ ]
[ ][ ][5][ ][ ]
[ ][ ][ ][ ][ ]

[ ][ ][8][ ][ ]
[ ][7][3][9][ ]
[6][2][1][4][A]
[ ][D][5][B][ ]
[ ][ ][C][ ][ ]

[ ][F][8][G][ ]
[E][7][3][9][H]
[6][2][1][4][A]
[L][D][5][B][I]
[ ][K][C][J][ ]

[M][F][8][G][N]
[E][7][3][9][H]
[6][2][1][4][A]
[L][D][5][B][I]
[P][K][C][J][O]

Clearly visible is the "snail" pattern. You always fill the outer neighbor cells of the previously filled cells.

Ignoring the outer bounds of the field the first iteration fills

1 cell - then
4 cells
8 cells
12 cells
... +4 cells

In terms of loops you should not loop using (i,j) which both reflect indices in the array. But rather loop over the rounds and then print the respective cells in that particular round. In round X you start in field arrayLength / 2 - X.

like image 125
luk2302 Avatar answered Oct 30 '25 05:10

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!