# Thread: Can someone explain this method to me?

1. Member Join Date
Oct 2013
Posts
63
Rep Power
0

## Can someone explain this method to me?

This was proposed as a possible solution for determining checks in tic-tac-toe.
I don't think I really understand why it works, how they could have possibly come up with this, or the math behind it.
In my program, the best I came up with was to brute force check systematically against a list of solutions that I had compiled.

I understand that the method works by checking the row and column coordinates of the last move made, and seeing if that move caused the player to win.
I don't understand why "(row ==col)||(col== -1* row+ (board.length-1));" would allow the program to know that it is on a diagonal, though. Along with the other if statements in the method.

Java Code:
``` public boolean isWinner(int row, int col){
String Player = Character.toString(board[row][col]);

boolean onDiagonal = (row ==col)||(col== -1* row+ (board.length-1));
boolean HorizontalWin = true;
boolean VerticalWin = true;
boolean DiagonalWinOne = true;
boolean DiagonalWinTwo = true;

for (int n = 0; n<board.length; n++){ //Checks rows and columns
if(!Character.toString(board[row][n]).equals(Player))
HorizontalWin = false;
if(!Character.toString(board[n][col]).equals(Player))
VerticalWin = false;
}
if(onDiagonal){ /*this check only passes if the move was a diagonal. if the move
was not a diagonal, then the method would have already returned.*/
for(int n = 0; n < board.length; n++){
if(!Character.toString(board[n][n]).equals(Player))
DiagonalWinOne = false;
if(!Character.toString(board[n][-1*n+(board.length-1)]).equals(Player))
DiagonalWinTwo = false;
}
}
else{
DiagonalWinOne = false;
DiagonalWinTwo = false;
}
boolean hasWon = (HorizontalWin || VerticalWin || DiagonalWinOne || DiagonalWinTwo);
return hasWon;
}```  Reply With Quote

2. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: Can someone explain this method to me?

There are only five places which can be on a diagonal. The first part is obvious (row=0, col=0, row=1, col=1, or row=2, col=2). The expression you question, IMHO, is poorly written. Try it this way and work it out on paper.

Java Code:
`boolean onDiagonal = (row ==col)||(col== (board.length-row-1);`
Regards,
Jim  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•