How to run through a 2d array with a single loop?

我的梦境 提交于 2019-12-08 04:00:19

问题


I was wondering if I could write this very thing but with one single loop, instead of two?

for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[0].length; col++) {
            if ((row + col) % 2 == 0) {
                System.out.print(matrix[row][col] + ", ");

                sum += matrix[row][col];
            }
        }

        System.out.println("with a sum of " + sum);
    }

Actually just ignore the body of the loop.. It's totally irrelevant, I have no idea whatsoever why I included it.. How to somehow combine the two for loops is my question.

Just keep it simple, if possible. Thank you!


回答1:


You can, though it's inefficient:

for(int i = 0 ; i < matrix.length * matrix[0].length ; i++)
     sum += matrix[i % matrix.length][i / matrix.length];

The basic idea would be to map each index to a value in a 2d-number space, using the fact that we know the length of each "row" of the array (matrix.length). We can compose a single index, that uniquely identifies two indices matrix[x][y], by z = x + y * matrix.length. The reverse of this would then be:

x = z % matrix.length
y = z / matrix.length

This depiction would be complete, e.g. each z in [0 , matrix.length * matrix[0].length) would identify exactly one pair of indices, thus we can use it here.




回答2:


Paul's answer is initially how I thought to do it. But there is the slight restriction that you need to have a rectangular two-dimensional array (i.e. the sub-arrays are all the same length). If you're modelling a "matrix", this is likely to be the case, but more generally you may want to sum up non-rectangular arrays.

A way around this is to do something like this:

for (int r = 0, c = 0; r < matrix.length;) {
  if (c < matrix[r].length) {
    sum += matrix[r][c];
    ++c;
  } else {
    c = 0;
    ++r;
  }
}

Although it's getting a bit messy. I'd just go for a nested loop instead.



来源:https://stackoverflow.com/questions/29202242/how-to-run-through-a-2d-array-with-a-single-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!