Reputation: 696
I have a function for checking if an array has three of the same character for a tic-tac-toe array. Trouble is, I'm having an issue with the logic:
for (int i = 0; i < SIZE; i++){
for (int j = 0; j < SIZE; j++){
if (board[i][j] != '*'){
if (i != j){
if (board[i][i] == board[i][j]){
matches++;
}
else if (board[i][j] == board[j][i]){
matches++;
}
else if (board[i][j] == board[j][j]){
matches++;
}
else if (board[i][j] == board[j][i]){
matches++;
}
else {
matches = 0;
}
}
}
}
}
It seems that I can check for horizontally and vertically for matchings. But, I can't quite figure out how to find the diagonal matchings. I thought this code would work and it so far has not.
Any suggestions about what is wrong?
Upvotes: 1
Views: 799
Reputation: 51832
Looks like homework, so I won't give a code solution. But you can tell when you're on a diagonal when either both indexes are equal (i == j
), or when the indexes add up to one less than the dimension of the matrix (i + j == SIZE - 1
.)
In the first case, you're on the first diagonal (top-left to bottom-right.) In the second case, you're on the second diagonal (top-right to bottom-left.)
This works for square matrices of any size.
Upvotes: 1