Hi, I am working on a OOP project and I have to see if any of my neighbouring 8 cells contains a specific value or not. Now I know how to find it but don't know which way will be more attractive to my employers.
The easiest and probably fastest way to do it is by hard coding it and checking for bounds. But I don't know if using other way is much preferred or what.
Thanks.
We would like to automate the process of bound checking and indexing to the 8 neighboring sites.
This function is quite useful for automating bounds checking:
1 2 3 4 5 6
bool inField( int r, int c )
{
if( r < 0 || r >= rows ) returnfalse;
if( c < 0 || c >= cols ) returnfalse;
returntrue;
}
and these arrays defining the 8 offsets to neighbors are handy too:
Sometimes you can avoid the bounds check altogether. If you have to store an NxN array, then store it in an (N+2)x(N+2) array where boundaries of this array are empty and the data is in indexes (1,1) to (N,N).
This technique works for some problems, such as a game board where you need to know if a piece has neighbors.
And of course, it's trading data space for code space and run time.