I need to rotate a given matrix 90º anticlockwise and I don't know how to start.
For example:
Go from this
5 10 8 9
16 30 25 41
7 17 50 12
45 8 22 34
to this:
9 41 12 34
8 25 50 22
10 30 17 8
5 16 7 45
This is like a matrix transpose. You can use a loop in a loop, or a stream in a stream:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}
};
int[][] arr2 = new int[d][d];
int[][] arr3 = new int[d][d];
int[][] arr4 = new int[d][d];
IntStream.range(0, d).forEach(i ->
IntStream.range(0, d).forEach(j -> {
// matrix transpose
arr2[j][i] = arr1[i][j];
// turn matrix 90º clockwise
arr3[j][d - 1 - i] = arr1[i][j];
// turn matrix 90º counterclockwise
arr4[d - 1 - j][i] = arr1[i][j];
}));
Arrays.stream(arr4).map(Arrays::toString).forEach(System.out::println);
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
Every cell [i][j]
in the original matrix becomes a cell [4-1-j][i]
in the rotated matrix:
int d = 4;
int[][] arr1 = {
{5, 10, 8, 9},
{16, 30, 25, 41},
{7, 17, 50, 12},
{45, 8, 22, 34}};
int[][] arr2 = new int[d][d];
for (int i = 0; i < d; i++)
for (int j = 0; j < d; j++)
arr2[d - 1 - j][i] = arr1[i][j];
for (int row = 0; row < d; row++)
System.out.println(Arrays.toString(arr2[row]));
// [9, 41, 12, 34]
// [8, 25, 50, 22]
// [10, 30, 17, 8]
// [5, 16, 7, 45]
See also:
• How do I rotate a matrix 90 degrees counterclockwise?
• Is there a way to reverse specific arrays in a multidimensional array?