We can directly print a rotated matrix without saving a result as follows: first we iterate over the columns and then the rows, and print the points. Since we don't know beforehand the length of the row, i.e the number of columns, we iterate up to the Integer.MAX_VALUE
and check at each step whether the columns are still present or not.
The rest of the algorithm is the same as when creating a transposed 2d array. The indices of points [i][j]
become [j][i]
, but the indices of one of the sides becomes equal to the length of the side, minus the current index of the side, minus 1
. Indexes start at 0.
int[][] array = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
for (int col = 0; col < Integer.MAX_VALUE; col++) {
boolean max = true;
for (int row = 0; row < array.length; row++) {
if (col < array[row].length) {
// System.out.printf("%2d ", // transposed matrix
// array[row][col]);
// System.out.printf("%2d ", // rotated 90º clockwise ⟳
// array[array.length - row - 1][col]);
System.out.printf("%2d ", // rotated 90º counterclockwise ⟲
array[row][array[row].length - col - 1]);
max = false;
}
}
System.out.println();
if (max) break;
}
Output (rotated 90º counterclockwise ⟲):
4 8 12
3 7 11
2 6 10
1 5 9
See also:
• Filling a jagged 2d array first by columns
• The transpose of a matrix