“Write a method in Java that returns true if there are k adjacent occurrences of a symbol in the same row, column, or diagonal of a checkered board (two-dimensional array), where k is the number of symbols inline desired.”
How can I do this? I have a rough idea of how to check rows and columns (very rough; no code, just thoughts) but I’m at a loss for checking the diagonal.
Edit: one other situation I’m thinking about: how can I check arbitrary positions? Right now, I’m only considering occurrences starting at (0,0), but what if there’s a string of 3 from, say, (2,3) to (2,6)? How could I keep track of multiple occurrences?
EDIT: Detecting the left diagonal (rough code for a question I posted in the comments below):
LeftDiagonal(x, symbol) {
noOfOccurence = 0;
for (currentX = (size - 1); currentX >= x; currentX--) {
if (board[currentX][currentX] == symbol) {
noOfOccurence++;
} else {
break;
}
}
return (noOfOccurence >= k);
}
The simplest (though not the most efficient as it may backtrack) solution that comes to mind is to write a recursive function, like the following psuedocode
This routine would, given a coordinate x,y, return the of symbols around it in a ‘blob’.
Note: This also means grouping of symbols such as 3 in a row, with 1 next to it in a column below.
If you were to call this once for every location in the matrix and see if the returned value once all recursive levels return is
>= k, that might solve your problem. Remember to do bounds checking so you do not check matrix[-1][-1] or anything.