Tic Tac Toe C++ Coding Challenge

Create a function that takes an array of char inputs from a Tic Tac Toe game. Inputs will be taken from player1 as "X", player2 as "O", and empty spaces as "#". The program will return the winner or tie results.

Examples

ticTacToe([
  ["X", "O", "O"],
  ["O", "X", "O"],
  ["O", "#", "X"]
]) ➞ "Player 1 wins"

ticTacToe([
  ["X", "O", "O"],
  ["O", "X", "O"],
  ["X", "#", "O"]
]) ➞ "Player 2 wins"

ticTacToe([
  ["X", "X", "O"],
  ["O", "X", "O"],
  ["X", "O", "#"]
]) ➞ "It's a Tie"


Notes

All inputs are valid (there will be no games where both players win).
Solution
c++

#include <iostream>
#include <vector>

std::string ticTacToe(const std::vector<std::vector<char>>& board) {
    // Check rows and columns
    for (int i = 0; i < 3; ++i) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '#') {
            return (board[i][0] == 'X') ? "Player 1 wins" : "Player 2 wins";
        }

        if (board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != '#') {
            return (board[0][i] == 'X') ? "Player 1 wins" : "Player 2 wins";
        }
    }

    // Check diagonals
    if ((board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '#') ||
        (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '#')) {
        return (board[1][1] == 'X') ? "Player 1 wins" : "Player 2 wins";
    }

    // Check for a tie
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            if (board[i][j] == '#') {
                return "It's a Tie";
            }
        }
    }

    return "Invalid input"; // This should not be reached if all inputs are valid
}

int main() {
    // Example usage:
    std::vector<std::vector<char>> gameBoard1 = {
        {'X', 'O', 'O'},
        {'O', 'X', 'O'},
        {'O', '#', 'X'}
    };

    std::cout << ticTacToe(gameBoard1) << std::endl; // Output: "Player 1 wins"

    std::vector<std::vector<char>> gameBoard2 = {
        {'X', 'O', 'O'},
        {'O', 'X', 'O'},
        {'X', '#', 'O'}
    };

    std::cout << ticTacToe(gameBoard2) << std::endl; // Output: "Player 2 wins"

    std::vector<std::vector<char>> gameBoard3 = {
        {'X', 'X', 'O'},
        {'O', 'X', 'O'},
        {'X', 'O', '#'}
    };

    std::cout << ticTacToe(gameBoard3) << std::endl; // Output: "It's a Tie"

    return 0;
}
Was this page helpful?