如何通过一个循环运行一个2D数组? [英] How to run through a 2d array with a single loop?

查看:160
本文介绍了如何通过一个循环运行一个2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(int)我想知道是否可以写这个东西,但只用一个循环而不是两个?行= 0;行< matrix.length;排++){
为(INT COL = 0; COL<矩阵[0]。长度; COL ++){
如果((行+ COL)% 2 == 0){
System.out.print(matrix [row] [col] +,);

sum + = matrix [row] [col];



System.out.println(和+);



$ b实际上只是忽略了循环体不知道为什么我包括它..如何以某种方式将结合为循环是我的问题。



只是保持简单,如果可能的话。谢谢!


解决方案

可以,虽然它是低效的:



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

基本思路是将每个索引映射到一个2d数字空间的值,事实上,我们知道数组的每个行的长度( matrix.length )。我们可以组成一个索引,它通过 z = x + y * matrix.length 来唯一标识两个索引 matrix [x] [y] / code>。然后反过来是:

$ p $ code $ x $ z $ matrix $ length
y = z / matrix.length

这个描述是完整的,例如在 [0,matrix.length * matrix [0] .length)中的每一个 z ,所以我们可以在这里使用它。


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!

解决方案

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.

这篇关于如何通过一个循环运行一个2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆