繁体   English   中英

先遍历二维数组行,然后先遍历列

[英]Traversing 2d array row first and then column first

我正在寻找一种方法来遍历 2d n by m int 数组 (int[col][row]),首先逐行(简单部分)然后逐列,在 Java 中。 这是逐行执行的代码,有没有办法逐行执行col?

for(int i = 0; i < display.length; i++){
            for (int j = 0; j < display[i].length; j++){
                if (display[i][j] == 1)
                    display[i][j] = w++;
                else w = 0;
            }
        }

由于您使用二维数组作为矩阵,我们可以假设整个矩阵中每行的长度相同(即每行的列数相同)。

//So, you can treat display[0].length as the number of columns.

for(int col=0; col<display[0].length; col++)
{
   for(int row=0; row<display.length; row++)
   {
      //your code to access display[row][col]
   }
}

希望这可以帮助!

如果行有那么多列,这是一种按列打印的方法。

String[][] twoDArray = new String[][] {
        new String[] {"Row1Col1", "Row1Col2", "Row1Col3"},
        new String[] {"Row2Col1", "Row2Col2"},
        new String[] {"Row3Col1", "Row3Col2", "Row3Col3", "Row3Col4"}
};

boolean recordFound = true;
int colIndex = 0;
while(recordFound) {
    recordFound = false;
    for(int row=0; row<twoDArray.length; row++) {
        String[] rowArray = twoDArray[row];
        if(colIndex < rowArray.length) {
            System.out.println(rowArray[colIndex]);
            recordFound = true;
        }
    }
    colIndex++;
}

输出是:

Row1Col1
Row2Col1
Row3Col1
Row1Col2
Row2Col2
Row3Col2
Row1Col3
Row3Col3
Row3Col4

由于 Java 数组的嵌套方式而不是矩形多维数组,这不是一件非常“自然”的事情。 例如,以下是可能的:

[ ][ ][ ]
[ ][ ]
[ ][ ][ ][ ][ ]

其中[ ]是一个元素。

垂直遍历这不是一个非常“自然”或有效的操作。 但是,您可以通过遍历列到数组长度的最大值来实现,通过显式检查避免数组ArrayOutOfBounds问题或(更邪恶)静默删除ArrayOutOfBounds异常。

编辑:在矩形情况下,只需切换两个循环。 您使用哪一行的长度并不重要。

static void columnFirst(List<List<Integer>> matrix) {
    int max = 0;
    for (int i = 0; i < matrix.size(); i++) {
        max = Math.max(max, matrix.get(i).size());
    }


    for (int i = 0; i < max; i++) {
        for (int j = 0; j < matrix.size(); j++) {
            if (matrix.get(j).size() > i)
                System.out.print(matrix.get(j).get(i) + " ");
        }
        System.out.println();
    }
}

输入数组

{{1, 2, 3, 4, 5, 6},
 {1, 2, 3},
 {1, 2, 3, 4, 5},
 {1},
 {1, 2, 3, 4, 5, 6, 7, 8, 9}}

输出:

1 1 1 1 1 
2 2 2 2 
3 3 3 3 
4 4 4 
5 5 5 
6 6 
7 
8 
9 
/* 
Assume that the length of the col[0] will be the same for all cols. 
Notice: that we are access salaries[j] for each iteration of j while
[i] same the same. 
*/

public void printColsValues() {
    for(int i = 0; i < array[0].length; i++) {
        for(int j = 0; j < array.length; j ++) {
            System.out.println(arr[j][i]);
        }
    }
}

暂无
暂无

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

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