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,
B, take turns placing characters,
'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[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 (
B). If the game ends in a draw, return
"Draw" and if there are still moves to be played, return
You can assume that
moves is valid, following the rules of tic-tac-toe, the grid is initially empty, and
A will play first.
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.
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.
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.
1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
- There are no repeated elements on
movesfollows the rules of tic-tac-toe.
Write the function
tictactoe in the provided
- Export your function as
tictactoefrom your file.
- Your function
tictactoeshould return a string, which is the winner of the game.
- The function should handle invalid or empty inputs and return a string "Invalid moves".