forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
squareMatrixRotation.js
37 lines (34 loc) · 1.06 KB
/
squareMatrixRotation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @param {*[][]} originalMatrix
* @return {*[][]}
*/
export default function squareMatrixRotation(originalMatrix) {
const matrix = originalMatrix.slice();
// Do top-right/bottom-left diagonal reflection of the matrix.
for (let rowIndex = 0; rowIndex < matrix.length; rowIndex += 1) {
for (let columnIndex = rowIndex + 1; columnIndex < matrix.length; columnIndex += 1) {
// Swap elements.
[
matrix[columnIndex][rowIndex],
matrix[rowIndex][columnIndex],
] = [
matrix[rowIndex][columnIndex],
matrix[columnIndex][rowIndex],
];
}
}
// Do horizontal reflection of the matrix.
for (let rowIndex = 0; rowIndex < matrix.length; rowIndex += 1) {
for (let columnIndex = 0; columnIndex < matrix.length / 2; columnIndex += 1) {
// Swap elements.
[
matrix[rowIndex][matrix.length - columnIndex - 1],
matrix[rowIndex][columnIndex],
] = [
matrix[rowIndex][columnIndex],
matrix[rowIndex][matrix.length - columnIndex - 1],
];
}
}
return matrix;
}