Reputation: 289
Say you want to check if someone won a game of tic tac toe. How would you do that, without just using an if statement to repeatedly check each column, row and diagonal for 3 in a row?
I'm sure there must be a way, some algorithm or technique that doesn't look anywhere near as ugly as 20 lines of ifs(or switches) to check an array of 9 for a winnar.
Upvotes: 2
Views: 362
Reputation: 726479
You are right, there is such technique.
Each winning pattern starts at the upper edge or at the left edge, and continues for three steps. In each of these steps, one of the following happens:
So now you can write a function like this:
bool CheckWin(char[3][3] board, char playerCh, int r, int c, int dr, int dc) {
for (int i = 0 ; i != 3 ; i++) {
if (board[r+i*dr][c+i*dc] != playerCh) {
return false;
}
}
return true;
}
Using this function, you can check if a player has three in a row starting at (r,c), with the step dr rows and dc columns:
bool won = false;
for (int i = 0 ; !won && i != 3 ; i++) {
won |= CheckWin(board, 'X', i, 0, 0, 1)
|| CheckWin(board, 'X', 0, i, 1, 0);
}
won |= CheckWin(board, 'X', 0, 0, 1, 1);
won |= CheckWin(board, 'X', 2, 0, -1, 1);
Upvotes: 1
Reputation: 2875
There are only eight winning positions possible. Convert to nine bit array and AND to test for win I.e.
Possible win patterns:
111000000 000111000 000000111 100100100 010010010 001001001 100010001 001010100
board:
OXO . X . XO
Testing X results in:
010010010
which ANDed with row 5 ==true
Upvotes: 2
Reputation: 2027
I'd probably go for a 9 bit int for each player representing their turns. You can easily apply bit operations to check for an entire column, row or diagonal directly.
Upvotes: 3