首先遍历2D阵列行,然后首先列



我正在寻找一种通过m int array(int [col] [row] [col] [row])逐行(简单零件)的2D N的方法爪哇。这是行行进行的代码,有没有办法通过col进行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例外。

编辑:在矩形情况下,只需切换两个循环。您使用哪个行的长度都没关系。

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

相关内容

最新更新