Simon Baars - 4 years ago 125
Java Question

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

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?

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download