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
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)
(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;
}
}
}