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
2010-10-30 10:17:55
But it would need a lot of conditions then, right? y less then array, y greater, x less, x greater
Mojmi
2010-10-30 10:18:57
It's better than catching exceptions which are for exceptional cases.
Darin Dimitrov
2010-10-30 10:20:51
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
2010-10-30 10:19:02
+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
2010-10-30 10:29:45