循环遍历 2D 数组的 2D 子数组的最佳方法是什么?
如果我有一个 2D 数组,则使用 for 循环遍历整个数组、行或列是很简单的。然而,有时,我需要遍历任意的二维子数组。
一个很好的例子是数独,我可以将整个网格存储在 2D 数组中,但随后需要分析 9 个正方形的每个单独块。目前,我会做类似以下的事情:
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.
}
}
是否有更好的方法来迭代任意子数组,特别是当它们以如上所述的常规模式出现时?
If I have a 2D array, it is trivial to loop through the entire array, a row or a column by using for loops. However, occasionally, I need to traverse an arbitrary 2D sub-array.
A great example would be sudoku in which I might store an entire grid in a 2D array but then need to analyse 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 sub-arrays especially when they occur in a regular pattern such as above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种循环结构的性能将是可怕的。考虑最里面的循环:
C 是“行优先”排序的,这意味着访问块将导致每次迭代时缓存未命中!这是因为内存不是连续访问的。
grid
也存在类似的问题。您的嵌套循环顺序是在改变j
之前修复i
,但您正在访问j
上的grid
作为行。这又不是连续的,并且会在每次迭代时缓存未命中。因此,处理嵌套循环和多维数组时的经验法则是以相同的顺序放置循环索引和数组索引。对于你的代码来说,那就是
The performance on this loop structure will be horrendous. Consider the inner most loop:
C is "row-major" ordered, which means that accessing
block
will cause a cache miss on each iteration! That's because the memory is not accessed contiguously.There's a similar issue for
grid
. Your nested loop order is to fixi
before varyingj
, yet you are accessinggrid
onj
as the row. This again is not contiguous and will cache miss on every iteration.So a rule of thumb for when dealing with nested loops and multidimensional arrays is to place the loop indices and array indices in the same order. For your code, that's
就数独而言,您不能只存储 9 个 3x3 数组吗?那么您就不需要为子数组烦恼...如果您开始移动到比数独更大的网格,您也可以通过这种方式提高缓存性能。
忽略这一点,您上面的代码可以正常工作。
Well in the case of sudoku couldn't you just store 9 3x3 arrays. Then you don't need to bother with sub arrays... If you start moving to much larger grids than sudoku you would improve cache performance this way as well.
Ignoring that, your code above works fine.
假设您有一个二维数组
a[n][m]
。为了循环右上角位于位置x,y
的子数组qx r
使用:对于您的数独示例,您可以这样做
Imagine you have a 2D array
a[n][m]
. In order to loop a subarrayq x r
whose upper right corner is at positionx,y
use:For your sudoku example, you could do this