简体   繁体   English

横向二维锯齿阵列,列优先

[英]Transverse 2D Jagged Array, Columns First

Given a 2D array named testing . 给定一个名为testing的2D数组。 I know how to transverse a jagged array, but it would start testing[0][0] and then go to testing[0][1] . 我知道如何横越锯齿状的数组,但是它将开始testing[0][0] ,然后去testing[0][1]

How would I transverse this jagged array starting at [0][0] and then going to [1][0] ? 我将如何从[0][0]开始到[1][0]横越这个锯齿状的数组?

Here is what I have tried thus far... 到目前为止,这是我尝试过的...

        for (int x = 0, counter = 0; x < testing[counter].length; x++) {
            for (int y = 0; y < testing.length; y++) {
                System.out.println(testing[y][x]);
        }

        counter++;
    }
}

The problem with iterating a jagged array on the inner index first, is knowing when to stop (that is the outer loop invariant) and knowing to skip processing the inner loop entirely (that is a break condition). 首先迭代内部索引上的锯齿形数组的问题是,知道何时停止(这是外部循环不变),并且知道完全跳过处理内部循环(这是break条件)。

To get the outer loop invariant, you could use a couple of different approaches. 要使外循环不变,可以使用几种不同的方法。 One simple way would be to compute the max inner index ahead of time. 一种简单的方法是提前计算最大内部索引。 A more efficient approach would be a do-while loop. 一种更有效的方法是do-while循环。 It checks a did-I-do-any-work boolean at the end of the loop, and continues if so. 它在循环结束时检查“我可以做任何工作”布尔值,如果是,则继续。 That way you don't have to precompute the max inner index. 这样,您不必预先计算最大内部索引。

To get the break condition, just check length of the array stored in the second dimension. 要获取中断条件,只需检查存储在第二维中的数组的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM