Say you're trying to visit an array in a checkerboard pattern:
0 1 2 3 4 5 6 7 0 o • o • o • o • 1 • o • o • o • o 2 o • o • o • o • 3 • o • o • o • o 4 o • o • o • o • 5 • o • o • o • o 6 o • o • o • o • 7 • o • o • o • o
So, say you're visiting the black elements here, and adding in all 4 white neighbours.
You can't do this at the edges or corners, because there are only 3 and 2 white neighbours there respectively. So you'd end up adding all 3 whites on the edges and 0 for out of bounds accesses.
The inefficient way to do this is to do something like
at each element
if element to the right is not out of bounds ...
But I don't want to be doing checks like this.
So what I did was cut the loop into strips, so:
at each element ON LEFT EDGE
add 3 elements i know are in bounds (right, up, down)
Then a special case for the very corners
at top left corner..
add 2 elements i know are in bounds (right, down)
So this ended up with a very long bit of code that works, but has no constraint checking. I'm looking for a way to cut down on the length of the code block though, and make it more maintainable.
Any tricks?