Find the Winner of a Tic Tac Toe Game
In this lab, you will be implementing a function to determine the winner of a tic-tac-toe game. Tic-tac-toe is a popular two-player game played on a 3 x 3
grid. The players, A
and B
, take turns placing characters, 'X'
and 'O'
respectively, into empty squares on the grid. The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal, or if all squares are non-empty and no moves can be played.
You are given a 2D integer array moves
where moves[i] = [rowi, coli]
indicates that the ith
move will be played on grid[rowi][coli]
. Your task is to implement a function tictactoe(moves)
that returns the winner of the game if it exists (A
or B
). If the game ends in a draw, return "Draw"
and if there are still moves to be played, return "Pending"
.
You can assume that moves
is valid, following the rules of tic-tac-toe, the grid is initially empty, and A
will play first.
Example 1:
const moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]; console.log(tictactoe(moves)); // Output: "A"
In this example, player A wins the game as they always play first.
Example 2:
const moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]; console.log(tictactoe(moves)); // Output: "B"
In this example, player B wins the game.
Example 3:
const moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]; console.log(tictactoe(moves)); // Output: "Draw"
In this example, the game ends in a draw since there are no moves to make.
Constraints:
1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
- There are no repeated elements on
moves
. moves
follows the rules of tic-tac-toe.
Write the function tictactoe
in the provided index.js
file.
Challenges
- Export your function as
tictactoe
from your file. - Your function
tictactoe
should return a string, which is the winner of the game. - The function should handle invalid or empty inputs and return a string "Invalid moves".