Reputation: 1853
I have a 2D array with a string at each index, such as:
+-----+-----+-----+
| h | l | o |
+-----+-----+-----+
| e | l | * |
+-----+-----+-----+
I know that you could print the array out through indices (0,0), (0,1), (0,2), (1,0), etc. through something like:
for (int k = 0; k < transpositionMatrix.length; k++) {
for (int k2 = 0; k2 < transpositionMatrix[k].length; k2++) {
System.out.print(transpositionMatrix[k][k2]);
}
}
However, I would like to access the elements through indices (0,0), (1,0), (2,0) ... (n,0), (0,1), (0,2) ... (0,m), where n
is number of rows and m
is the number of columns at row m
.
To put this another way, I would like to read "down" each column instead of across each row.
Using the above 2D array as an example, reading down each column would print "hello*" and reading across each row would print "hloel*". I would like to achieve the former.
How can this be done using Java?
Note that all rows are assumed to be the same length.
Upvotes: 2
Views: 7174
Reputation: 66
The method of accessing an array that you are looking for is called Column-Major ordering. See wikipedia for the difference between Column-Major and Row-Major ordering.
To solve your problem, the inner for loop should iterate over all the rows, before the outer for loop changes the column number.
The for loop will look like this:
for (int column = 0; column < transpositionMatrix[0].length; column++) {
for (int row = 0; row < transpositionMatrix.length; row++) {
System.out.print(transpositionMatrix[row][column]);
}
}
Upvotes: 3
Reputation: 1371
for (int k = 0; k < transpositionMatrix.length[0]; k++) {
for (int k2 = 0; k2 < transpositionMatrix.length; k2++) {
System.out.print(transpositionMatrix[k2][k]);
}
}
It's pretty much just flipping the for-loops.
Upvotes: 1