Added general row/column searching logic

This commit is contained in:
Brychan Dempsey 2021-10-04 11:35:22 +13:00
parent 1524b0f414
commit 22c4c29138

View File

@ -8,15 +8,69 @@ namespace Week_11___TTTLib
{
public class GameWinnerService : IGameWinnerService
{
private const char NO_WINNER = ' ';
public char Validate(char[,] board)
{
var rowOne = board[0,0];
var rowTwo = board[0,1];
var rowThree = board[0,2];
if (rowOne == rowTwo && rowTwo == rowThree)
return rowOne;
return CheckRow(board,2);
}
return ' ';
private static char CheckRow(char[,] board, int rowLimit=2)
{
char leftDiag = board[0, 0];
char rightDiag = board[rowLimit, 0];
for (int row = 0; row < rowLimit; row++)
{
char rowResult = board[0,row];
char colResult = board[row, 0];
// loop through the row and check it; reset the value if not correct
for (int col = 1; col < rowLimit; col++)
{
if (board[col, row] != rowResult)
{
rowResult = NO_WINNER;
break;
}
}
// loop through the col and check it; reset the value if not correct (transposed)
for (int col = 1; col < rowLimit; col++)
{
if (board[row, col] != colResult)
{
colResult = NO_WINNER;
break;
}
}
// Verify the the results were won
if (rowResult != NO_WINNER)
return rowResult;
else if (colResult != NO_WINNER)
return colResult;
// Verify diagonals
if (board[row, row] != leftDiag)
{
leftDiag = NO_WINNER;
}
if (board[rowLimit - row, row] != rightDiag)
{
rightDiag = NO_WINNER;
}
}
if (leftDiag != NO_WINNER)
return leftDiag;
if (rightDiag != NO_WINNER)
return rightDiag;
// return no result otherwise
return NO_WINNER;
}
}