Working on the problem Find Winner on a Tic Tac Toe Game, I took several hours longer than an artificial time constraint the site had for mock interview purposes. This leads me to wonder if my solution is needlessly complex or unclear. Curious to hear from others. The only part that would have to stay the same upon review is the function signature func tictactoe(_ moves: [[Int]]) -> String
for the web editor to accept it.
class Solution {
func tictactoe(_ moves: [[Int]]) -> String {
let populatedBoard = populatedBoard(with: moves)
if let winner = checkWon(board: populatedBoard) {
return winner
}
if moves.count < 9 {
return "Pending"
} else {
return "Draw"
}
}
func populatedBoard(with moves: [[Int]]) -> [[Character]] {
var playerAMoves = [[Int]]()
var playerBMoves = [[Int]]()
var board: [[Character]] = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]
]
for (index, move) in moves.enumerated() where index % 2 == 0 {
playerAMoves.append(move)
}
for (index, move) in moves.enumerated() where index % 2 == 1 {
playerBMoves.append(move)
}
for move in playerAMoves {
board[move[0]][move[1]] = "X"
}
for move in playerBMoves {
board[move[0]][move[1]] = "O"
}
return board
}
func checkWon(board: [[Character]]) -> String? {
for index in 0...2 {
// Player won horizontally in a row.
if board[index][0] == board[index][1] && board[index][0] == board[index][2] {
if board[index][0] == "X" {
return "A"
} else if board[index][0] == "O" {
return "B"
}
}
// Player won vertically in a column.
if board[0][index] == board[1][index] && board[0][index] == board[2][index] {
if board[0][index] == "X" {
return "A"
} else if board[0][index] == "O" {
return "B"
}
}
}
// Player won diagonally between the top left and bottom right.
if board[0][0] == board[1][1] && board[0][0] == board[2][2] {
if board[0][0] == "X" {
return "A"
} else if board[0][0] == "O" {
return "B"
}
}
// Player won diagonally between the top right and bottom left.
if board[0][2] == board[1][1] && board[0][2] == board[2][0] {
if board[0][2] == "X" {
return "A"
} else if board[0][2] == "O" {
return "B"
}
}
return nil
}
}