Created
March 15, 2013 16:32
-
-
Save charlespunk/5171165 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Design an algorithm to figure out if someone has won a game of tic-tac-toe for N*N. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Piece hasWon(Piece[][] board){ | |
//test row | |
for(int i = 0; i < board.length; i++){ | |
if(board[i][0] == Piece.EMPTY) continue; | |
for(int j = 1; j < board[0].length; j++){ | |
if(board[i][j] != board[i][j - 1]) break; | |
if(j == board[0].length - 1) return board[i][0]; | |
} | |
} | |
//test column | |
for(int i = 0; i < board[0].length; i++){ | |
if(board[0][i] == Piece.EMPTY) continue; | |
for(int j = 1; j < board.length; j++){ | |
if(board[j][i] != board[j - 1][i]) break; | |
if(j == board.length - 1) return board[0][i]; | |
} | |
} | |
//test diagonal (top left -> bottom right) | |
if(board[0][0] != Piece.Empty){ | |
for(int diagonal = 1; diagonal < board.length; diagonal++){ | |
if(board[diagonal][diagonal] != board[diagonal - 1][diagonal - 1]) break; | |
if(diagonal == board.length - 1) return board[0][0]; | |
} | |
} | |
//test diagonal (top right -> bottom left) | |
if(board[0][board[0].length - 1] != Piece.Empty){ | |
for(int diagonal = 1; diagonal < board.length; diagonal++){ | |
if(board[diagonal][board[0].length - 1 - diagonal] != board[diagonal - 1][board[0].length - 1 - diagonal - 1]) break; | |
if(diagonal == board.length - 1) return board[0][0]; | |
} | |
} | |
return Piece.EMPTY; | |
} | |
public enum Piece{ | |
EMPTY, BLACK, WHITE | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment