Glad the loop is working. Please try a bit harder to reason out that code. If I do anything more I'm writing it for you.
The 9, located at row9, col9 may have up to 4 neighbors (if it's dead center in the array) or as little as 2 (corners). The left neighbor is located at:
row9, col9-1 = left neighbor. but if col9 = 0 you can't check that spot, it's not in the array!
See the last 3 lines in my previous post for the locations of the other 3 neighbors. You need to check those locations for x, but only if they're on the board.
edit: We're writing the function for the neighbor check with code explicitly for each of the 4 cases.
When we get a little more comfortable with this stuff we can generalize the code and do the 4 checks in a loop.
I'm doing very similar things in the minesweeper code where I visit all the neighbors of a given space.
I do this when finding all the neighboring mine counts in createFIeld(), and when clearing around a space with no neighboring mines in clearSpace().
So yes, what you learn from this exercise is relevant.
Here's what you need to do the search here like I do in my minesweeper code.
You will need a function to check that a position is in the array, like the one from minesweeper:
bool isInField( int r, int c );// validates position
This will do for here:
1 2 3 4 5 6
|
bool isInArray( int r, int c )
{
if( r < 0 || r > 2 ) return false;
if( c < 0 || c > 2 ) return false;
return true;
}
|
Then, is9neighbor may be written like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
bool is9neighbor( int x, int& rx, int& cx, int row9, int col9 )// discouraging global variables. Pass them
{
// neighbor positions
const int r[4] = { row9, row9, row9+1, row9-1};// visit order
const int c[4] = { col9-1, col9+1, col9, col9 };// left, right, bottom, top
for( int i=0; i<4; ++i )
{
if( isInArray( r[i],c[i] ) && random_matrix[ r[i] ][ c[i] ] == x )
{
rx = r[i];
cx = c[i];
return true;
}
}
return false;
}
|