Created
February 2, 2016 21:03
-
-
Save giannispan/18d9b271485a07a147b6 to your computer and use it in GitHub Desktop.
We want our function to return -1 if the board is not solved yet, 1 if X won, 2 if O won, or 0 if it's a cat's game (i.e. a draw). You may assume that the board passed in is valid in the context of a game of Tic-Tac-Toe.
This file contains 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
function isSolved(board) { | |
if ((board[0][0] == 1 && board[0][0] == board[1][1] && | |
board[1][1] == board[2][2]) || (board[0][2] == 1 && board[0][2] == board[1][1] && | |
board[1][1] == board[2][0])) return 1; | |
else if ((board[0][0] == 2 && board[0][0] == board[1][1] && | |
board[1][1] == board[2][2]) || (board[0][2] == 2 && board[0][2] == board[1][1] && | |
board[1][1] == board[2][0])) return 2; | |
for (var i =0; i<3; i++) | |
{ | |
if(board[i][0] == board[i][1] && | |
board[i][1] == board[i][2] && board[i][0] == 1 && board[i][1] == 1 | |
&& board[i][2] == 1) return 1; | |
else if (board[i][0] == board[i][1] && | |
board[i][1] == board[i][2] && board[i][0] == 2 && board[i][1] == 2 | |
&& board[i][2] == 2) return 2; | |
} | |
for (var i =0; i<3; i++) | |
{ | |
if (board[0][i] == board[1][i] && | |
board[1][i] == board[2][i] && board[0][i] == 1 && board[1][i] == 1 | |
&& board[2][i] == 1) return 1; | |
else if (board[0][i] == board[1][i] && | |
board[1][i] == board[2][i] && board[0][i] == 2 && board[1][i] == 2 | |
&& board[2][i] == 2) return 2; | |
// else if (board[i][i] == 0) return -1; | |
} | |
for (var i =0; i<3; i++) | |
{ | |
for (var j = 0; j < 3; j++){ | |
if (board[i][j] == 0) | |
return -1; | |
} | |
} | |
for (var i =0; i<3; i++) | |
{ | |
for (var j = 0; j < 3; j++){ | |
if (board[i][j] != 0) | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment