簡體   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