如何使用单个循环运行二维数组? [英] How to run through a 2d array with a single loop?

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

问题描述

我想知道我是否可以只用一个循环而不是两个循环来写这个东西?

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);
    }

实际上只是忽略循环的主体..这完全无关紧要,我不知道为什么要包含它..如何以某种方式组合两个 for 循环是我的问题.

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];

基本的想法是将每个索引映射到二维空间中的一个值,利用我们知道数组的每一行"的长度(matrix.length).我们可以通过z = x + y * matrix.length 组合一个索引,唯一标识两个索引matrix[x][y].反过来就是:

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

此描述将是完整的,例如[0 , matrix.length * matrix[0].length) 中的每个 z 都可以准确地标识一对索引,因此我们可以在这里使用它.

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.

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

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