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.

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;

}

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.

Code:

`boolean onDiagonal = (row ==col)||(col== (board.length-row-1);`

Regards,

Jim