I have a 5×5 2D array in C#. I need to check the 2 spaces above, below, right and left of the array. What is the best way to do this? The try catch statements are for when it has to check a point that would be out of bounds.
This is what I have so far, and it works, but it just looks sloppy.
bool[,] boardSpaces = new bool[5, 5] {
{ true, true, true, true, true },
{ true, true, true, true, true },
{ true, true, true, true, true },
{ true, true, true, true, true },
{ true, true, true, true, true }
};
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
if (boardSpaces[x, y] == false)
{
try
{
if (boardSpaces[x - 1, y] == true && boardSpaces[x - 2, y] == true)
{
validMoveRemaining = true;
break;
}
}
catch { }
try
{
if (boardSpaces[x + 1, y] == true && boardSpaces[x + 2, y] == true)
{
validMoveRemaining = true;
break;
}
}
catch { }
try
{
if (boardSpaces[x, y - 1] == true && boardSpaces[x, y - 2] == true)
{
validMoveRemaining = true;
break;
}
}
catch { }
try
{
if (boardSpaces[x, y + 1] == true && boardSpaces[x, y + 2] == true)
{
validMoveRemaining = true;
break;
}
}
catch { }
}
}
}
Instead of exception handling, use arithmetic bounds checking. You already have the row and column index as well as the dimensions of the matrix. Why don’t you simply if() that?
You can even make a compound boolean expression out of it:
There you go! 🙂