Search code examples
algorithmartificial-intelligencetic-tac-toe

Tic tac toe algorithm 5x5 table with 4 in a row


I was asked to make a tictactoe algorithm however i dont quite understand how can i check if each row or columns can become an ending state.

I tried it with 5x5 however i can only do it with a 5 in row so i was hoping i there is a way for me to do it if the ending state requires 4 in a row. I have not yet considered the diagonals so i can just focus on the column and row checking.

my checker looks like this

var B = this.board;

    //check rows
    for(var i = 0; i <= 20; i = i + 5) {
        if(B[i] !== "E" && B[i] === B[i + 1] && B[i + 1] == B[i + 2] && B[i + 2] == B[i + 3] && B[i + 3] == B[i + 4]) {
            this.result = B[i] + "-won"; //update the state result
            return true;
        }
    }

    //check columns
    for(var i = 0; i <= 4 ; i++) {
        if(B[i] !== "E" && B[i] === B[i + 5] && B[i + 5] === B[i + 10] && B[i + 10] === B[i + 15])  && B[i +15] === B[i + 20]{
            this.result = B[i] + "-won"; //update the state result
            return true;
        }
    }

    var available = this.emptyCells();
    if(available.length == 0) {
        //the game is draw
        this.result = "draw"; //update the state result
        return true;
    }
    else {
        return false;
    } 

Solution

  • You can just iterate over top rows (from 0 to 1, inclusively) and all columns and check that the sequence of 4 cells in this column starting in the given row and going down consists of the same element.

    You can do the same thing for rows by iterating over leftmost columns (again, from 0 to 1) and all rows and checking if the sequence that goes right.