tags:

views:

48

answers:

3

Hi, I am making game of life in 2D array. I need to determine when all adjacent cells are empty so I just test all of them. It works well unless the cell being checked is the boundary. Then of course testing X+1 throws an exception as the index is out of the array boundaries. Can I handle this somehow instead of handling the exception? Thanks

+1  A: 

Yes, before accessing the element at index i + 1, check whether i + 1 is strictly inferior to array.Length.

Darin Dimitrov
But it would need a lot of conditions then, right? y less then array, y greater, x less, x greater
Mojmi
It's better than catching exceptions which are for exceptional cases.
Darin Dimitrov
A: 

use:

GetLength(0)
GetLength(1)

to get the width and height of the array.

There is also a neat performance trick the runtime uses for it's own bounds checks: casting to unsigned int to make the two checks into one. But of course this costs readability, so only use it if it's really performance critical.

(i>=0)&&(i<length)
becomes
(uint)i<length
CodeInChaos
+1  A: 

If you want speed you'll have to threat the edge-cells differently and process the rest with a

 for(int x = 1; x < Size-1; x++)  // these all have x-1 and x+1 neighbours
Henk Holterman