If I have a 2D array, it is trivial to scroll through the entire array, row or column using for loops. However, sometimes I need to traverse an arbitrary 2D array.
A good example is Sudoku, in which I could store the entire grid in a 2D array, but then I need to analyze each individual block of 9 squares. Currently, I would do something like the following:
for(i = 0; i < 9; i += 3) {
for(j = 0; j < 9; j += 3) {
for(k = 0; k < 3; k++) {
for(m = 0; m < 3; m++) {
block[m][k] == grid[j + m][i + k];
}
}
//At this point in each iteration of i/j we will have a 2D array in block
//which we can then iterate over using more for loops.
}
}
Is there a better way to iterate over arbitrary subarrays, especially when they occur in a regular pattern like the one above?
source
share