Hi everyone,
I'v been bored so I created a small console minesweeper game and while writting it I had to find the neighbor positions of an element in a size*size matrix which is represented as an vector of elements and one variable which holds the size value. I didn't want to return the actual values of the neighbor elements but their positions so that I could use that as a public function (otherwise the client could see where the mines are at :P).
For example for field eq 0 and size eq 3 the function should return {1, 3, 4}:
1 0 0 0 1 0
0 0 0 => 1 1 0
0 0 0 0 0 0
Well, basicaly it looks like this:
vector<int> adjecantPositions(int field, int size)
{
int row = field / size;
int col = field % size;
vector<int> result;
/*
1 0 0
1 0 0
1 0 0
*/
if (col > 0)
{
result.push_back(calcField(row, col-1, size));
if (row > 0)
result.push_back(calcField(row-1, col-1, size));
if (row < size - 1)
result.push_back(calcField(row+1, col-1, size));
}
/*
0 0 1
0 0 1
0 0 1
*/
if (col < size - 1)
{
result.push_back(calcField(row, col+1, size));
if (row > 0)
result.push_back(calcField(row-1, col+1, size));
if (row < size - 1)
result.push_back(calcField(row+1, col+1, size));
}
/*
0 1 0
0 0 0
0 1 0
*/
if (row > 0)
result.push_back(calcField(row-1, col, size));
if (row < size - 1)
result.push_back(calcField(row+1, col, size));
return result;
}
calcField(int, int, int) is just converting coordinates into field number (row*size + col).
This is a fast solution but it's not elegant and I bet there's some better way to do this. Any ideas?