Home > Blockchain >  Finding out Horizontal/Vertically aligned markers in a matrix
Finding out Horizontal/Vertically aligned markers in a matrix

Time:10-28

How do I go about solving the tic-tac-toe problem in C#.

The rule of the game is , in a 3*3 square board players take turns alternatively. A player wins when he has 3 markers aligned horizontally or vertically.

player1Marker =  new List<(int x, int y)>
    {
       (x:2, y:2),
       (x:1, y:1),
       (x:0, y:2),
       (x:2, y:0),
    }

player2Marker =  new List<(int x, int y)>
        {
           (x:0, y:1),
           (x:0, y:0),
           (x:1, y:2)
        }

The game starts from player1 . Player1 1st move : [2,2] Player2 1st move : [0,1] and so on.

Player 1 wins with output as [[1,1],[0,2],[2,0]]

public List<(int x, int y)> GetWinningCombo(List<(int x, int y)> player1Markers, List<(int x, int y)> player2Markers)
    {
        
        return new List<(int x, int y)>();
    }

CodePudding user response:

Here is one way to do it:

    public List<(int x, int y)> GetWinningCombo(List<(int x, int y)> player1Markers, List<(int x, int y)> player2Markers)
    {
        // make the board
        int[,] brd = new int[3, 3];
        // add player1 markers
        foreach ((int x, int y) mrk in player1Markers)
        {
            brd[mrk.x, mrk.y] = 1;
        }
        // add player2 markers
        foreach ((int x, int y) mrk in player2Markers)
        {
            brd[mrk.x, mrk.y] = 2;
        }

        // check horizontals
        for(int i=0; i<=2; i  )
        {
            if (brd[i, 0] > 0 && brd[i, 0] == brd[i, 1] && brd[i, 1] == brd[i, 2])
                return new List<(int x, int y)> { (i, 0), (i, 1), (i, 2) };
        }

        // check veritcals
        for (int i = 0; i <= 2; i  )
        {
            if (brd[0, i] > 0 && brd[0, i] == brd[1, i] && brd[1, i] == brd[2, i])
                return new List<(int x, int y)> { (0, i), (1, i), (2, i) };
        }

        // check diagonals
        if (brd[0, 0] > 0 && brd[0, 0] == brd[1, 1] && brd[1, 1] == brd[2, 2])
            return new List<(int x, int y)> { (0, 0), (1, 1), (2, 2) };
        if (brd[2, 0] > 0 && brd[2, 0] == brd[1, 1] && brd[1, 1] == brd[0, 2])
            return new List<(int x, int y)> { (2, 0), (1, 1), (0, 2) };

        // no wins, return empty list
        return new List<(int x, int y)>();
    }
  • Related