3
\$\begingroup\$

After some hours of coding trying to implement "algorithms" to make a Tic-Tac-Toe game, I came up with something I'm not really proud of.

Here's the code:

const TicTacToe = (function(){

    const grids = document.querySelectorAll(".box");
    const winning_combinations = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    let turn = 'X';
    let marks = 0;
    let currPos = void 0;

    for(let i = 0, len = grids.length; i < len; ++i)
        grids[i].addEventListener("click", () => mark( (currPos=i) )  );

    function mark(pos){
        if(grids[currPos].textContent != '')
            return alert("grid taken!");

        grids[currPos].textContent = turn;

        if(!foundWinner())
            turn = (turn === 'X') ? 'O' : 'X';
        else
            win();

    }   

    function foundWinner(){

        for(let currSet = 0, len = winning_combinations.length; currSet < len; ++currSet){

            winning_combinations[currSet].forEach(pos => {
                if(grids[pos].textContent == turn){
                    marks++;
                }               
            });

            if(marks == 3){
                return true;
            }
            else{
                marks = 0;
            }
        }

        return false;

    }

    function win(){
        return alert(turn + " won!");
    }

    return{
        reset: function(){
            // todo
        }
    }

}) ();

The issue is that I am pretty sure this code has O(n log n) time complexity, and I would love to make it at least O(n). I've tried creating possible combinations based on what grid the player pressed—opposed to trying all the winning combinations—but no avail.

If there is any way I can better this code or make it more efficient, please let me know!

\$\endgroup\$
2
  • \$\begingroup\$ Computational complexity is usually only something to worry about when you have inputs of significant sizes. If you have a static 3x3 grid with a static 8 possible winning positions to iterate over, I don't see what a theoretical bottleneck could be; those numbers are very small. (unless something is auto-clicking and restarting games in a very tight loop, which sounds like it isn't the case) \$\endgroup\$ Commented Apr 6, 2020 at 3:33
  • \$\begingroup\$ Can you clarify the sort of performance improvements you're looking for? \$\endgroup\$ Commented Apr 6, 2020 at 5:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.