Home > Blockchain >  cross match 2d array
cross match 2d array

Time:03-25

trying to implement a bigger scale of tic tac toe game

this game can have more than 3 rows and columns

whenever a 4 consecutive pattern is found(horizantal,vertical or cross)

the player is the winner

i already found the horizantal and vertical mathcing implemantation

but can't find a way to identify the cross pattern of a certain charcter inside a 2d array

consider the following 2d array

`

        char[][] char2d={
            {'*','o','o','*'},
            {'o','*','o','o'},
            {'o','o','*','o'},
            {'o','o','o','*'}
    }

`

how can i check if the '*' character has four consecutive cross pattern in this 2d array

CodePudding user response:

This function returns true if the given start position is a downwards diagonal (as drawn in your picture, advancing left-to-right) of length s full of character c.

public static void isFullDownDiagonal(char[][] board, 
         int startCol, int startRow, int s, char c) {

   for (int i=0; i<s; i  ) {
      if (board[startRow i][startCol i] != c) return false; 
                     //  \_ change this sign to test up diagonal         
   }
   return true;
}

With a small change you can test for the upwards diagonal. And in an NxNboard there can only be starts-of-diagonal in a (N-s 1)x(N-s 1) area at the top-left and bottom-corners.

CodePudding user response:

Another one...

  public static void main(String[] args) {       
    char[][] char2d={
      {'*','o','o','*'},
      {'o','*','o','o'},
      {'o','o','*','o'},
      {'o','o','o','*'}
    };
    System.out.println(hasCross(char2d, '*'));
  }

  public static boolean hasCross(char[][] board, char c) {
    // Assumes a SQUARE board!
    boolean crossA = true;
    boolean crossB = true;
    for(int col=0, rowA=0, rowB=(board.length-1); col<board.length; col  , rowA  , rowB--) {
      if (board[rowA][col]!=c) {
        crossA = false;
      }
      if (board[rowB][col]!=c) {
        crossB = false;
      }
    }
    return crossA || crossB;
  }

CodePudding user response:

You can use IntStream to check if the diagonals have only '*':

public static boolean checkDiagonals(char[][] arr) {
    int dimension = arr.length;
    return IntStream.range(0, dimension)
            .allMatch(i -> arr[i][i] == '*') 
    || IntStream.range(0, dimension)
            .allMatch(i -> arr[i][dimension - i - 1] == '*');
}
  • Related