GameLogic, x in a row game

前端 未结 2 1624
耶瑟儿~
耶瑟儿~ 2021-01-27 07:20

I\'m making a game and I need to make a method which checks if the specified cell is part of a horizontal consecutive sequence of cells containing the same character. The sequen

相关标签:
2条回答
  • 2021-01-27 07:56

    Suppose the column you want to include is - 5. And length of sequence is 3.

    Now, here are the possibilities of the occurence of your sequence in that row: -

    • Col = (5 - 2) to 5
    • Col = 5 to (5 + 2)
    • Or, anywhere in between the range [(5 - 2), (5 + 2)]

    So, the range you are interested in is: - [col - length + 1, col + length - 1]. In this range, every sequence of length 3 will include your column 5.

    So, simply run the loop between these range. Now, the problem will be when those range goes out of range. So, you can do that check before.

    A better way would be to use Math.max(0, col-length+1), and Math.min(col + length-1, arraylength).

    So, you can use this for-loop: -

    public static boolean checkPositionRow(char[][] a, int row, int col, int l) {
    
      int counter = 0;
      int left = col - l + 1;
      int right = col + l - 1;
      char charAtPosition = a[row][col];
    
      for (int i = Math.max(0, left); i < Math.min(right, a[row].length); i++) {
            if (a[row][i] == charAtPosition) {
                counter++;
                if (counter >= l)
                    return true;
    
            } else {
                counter = 0;
            }
      }
    }
    
    0 讨论(0)
  • 2021-01-27 07:57

    You can simply search for both sides using two loops (one per side) and check if the sum of consecutive cells is indeed l. Something along the lines of:

    public static boolean checkPositionRow(char[][] a, int row, int col, int l) {
        int counter = 1; //starting from 1, because for a[row][col] itself
        char charAtPosition = a[row][col];
       //expand to the right as much as possible
        for (int i = col+1; i < a[row].length && a[row][i] == charAtPosition; i++) counter++;
       //expand to the left as much as possible
        for (int i = col-1; i >= 0 && a[row][i] == charAtPosition; i--) counter++;
        return counter >= l;
    }
    
    0 讨论(0)
提交回复
热议问题