-1

I have an 2D array in java (example)

0|0|0|0
1|1|1|0
0|1|0|1

I need to create code that says if the items around the square are something, do something. I can do this however I have an issue.

If the item is on an edge the array needs to effectively wrap, so that the top row is next to the bottom row.

Does anyone know how to do this?

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
Daniel k
  • 13
  • 6
  • Not clear why it needs to wrap. And what is "are do something" exactly. – RealSkeptic Feb 15 '17 at 17:14
  • you seem to contradict yourself, you say you can find items around the square but then state you can't find items on the edge? how is finding something around the square and finding an item on the edge different? – RAZ_Muh_Taz Feb 15 '17 at 17:15
  • 1
    Wait ... are you asking how you treat the array as if opposite edges were adjacent? – Andy Thomas Feb 15 '17 at 17:17
  • maybe I'm wrong then if I'm say using the top left square then the the bottom left bottom right and top right need to surround it. – Daniel k Feb 15 '17 at 17:18

1 Answers1

0

First, identify whether you're interested in the 4-connected neighborhood or 8-connected. The 4-connected neighborhood are the cells above, left, right and below a cell. The 8-connected neighborhood are the same cells plus the diagonal.

Now, you just need a way to compute the indices of a particular cell.

Here's an example for computing the column index to the left of another.

int getLeftIndex( int index, int width ) {
   int rv = index - 1;
   if ( index < 0 ) { index = width - 1; }
   return rv;
}

Similar methods can compute the column index to the right, or the row index above or below.

Call two methods to get both the appropriate row and column.

You could also generalize this to provide a single method that accepts a delta in either direction, so that you could loop over the cells.

public static int getCoord( int from, int delta, int size ) {
    return Math.floorMod( from + delta,  size); // Requires Java 8
}

Java also provides a modulus operator, but it won't give you the results you want.

Here's an example of looping over the 8-connected cells around another:

public static void main(String[] args) {
    int x = 0;
    int y = 0;
    int size = 4;

    for ( int i = -1; i <= 1; ++i ) {
        for ( int j = -1; j <= 1; ++j ) {
            if ( i != 0 || j != 0 ) {
                int xij = getCoord( x, i, size );
                int yij = getCoord( y, j, size );
                System.out.println( "x=" + xij + "  y=" + yij );
            }
        }
    }

}
Community
  • 1
  • 1
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151