Problems › JavaScript › games
Who won the tic-tac-toe game
A completed 3x3 tic-tac-toe board is given. Determine which player won, or if it is a draw.
- The board is a 3x3 grid of integers: 0 means empty, 1 is player one, 2 is player two.
- A player wins by filling an entire row, column, or diagonal with their value.
- Return the winning player's number, or 0 if nobody won.
ticTacToeWinner(board: list<list<int>>) → int
Where you start
function ticTacToeWinner(board) {
}
Worked examples
| Call | Result |
|---|---|
ticTacToeWinner([[1,1,1],[0,2,0],[2,0,2]]) | 1 |
ticTacToeWinner([[2,0,1],[2,0,1],[2,1,0]]) | 2 |
ticTacToeWinner([[1,2,1],[0,1,2],[2,0,1]]) | 1 |
ticTacToeWinner([[0,1,2],[1,2,0],[2,0,0]]) | 2 |
Hint
Check all three rows, all three columns, and both diagonals.
Reference solution in JavaScript
function ticTacToeWinner(board) {
for (let i = 0; i < 3; i++) {
if (board[i][0] !== 0 && board[i][0] === board[i][1] && board[i][1] === board[i][2]) return board[i][0];
if (board[0][i] !== 0 && board[0][i] === board[1][i] && board[1][i] === board[2][i]) return board[0][i];
}
if (board[0][0] !== 0 && board[0][0] === board[1][1] && board[1][1] === board[2][2]) return board[0][0];
if (board[0][2] !== 0 && board[0][2] === board[1][1] && board[1][1] === board[2][0]) return board[0][2];
return 0;
}