Reputation: 2289
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?
Upvotes: 4
Views: 1588
Reputation: 57124
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 round
s and then print the respective cells in that particular round. In round X
you start in field arrayLength / 2 - X
.
Upvotes: 6
Reputation: 2682
The basic looop is as follows -
K=1;
while(true) {
k=K-1;
for(n=0; n<=k; n++)
x=-k+n; y=-n;
for(n=1; n<=k; n++)
x=n; y=-k+n;
for(n=1; n<=k; n++)
x=k-n; y=n;
for(n=1; n<=k-1; n++)
x=-n; y=k-n;
if x out of bounds or y out of bounds continue;
K++;
if(K>N/2) break;
}
where N is the size of the array (width or height) and K is the cycle where K=1 at the center.
To find the x y coordinates you go in four loops upper left upper right .... - and since the coordinate system is located at N/2, N/2 you have to add that to x y. There are K+2(K-1)+(K-2) elements in each cycle
Upvotes: 1