Add square matrix rotation in-place algorithm.

This commit is contained in:
Oleksii Trekhleb
2018-07-06 08:15:56 +03:00
parent 17ad4dc4d1
commit 75133592bb
4 changed files with 178 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
/**
* @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) {
const tmp = matrix[columnIndex][rowIndex];
matrix[columnIndex][rowIndex] = matrix[rowIndex][columnIndex];
matrix[rowIndex][columnIndex] = tmp;
}
}
// 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) {
const mirrorColumnIndex = matrix.length - columnIndex - 1;
const tmp = matrix[rowIndex][mirrorColumnIndex];
matrix[rowIndex][mirrorColumnIndex] = matrix[rowIndex][columnIndex];
matrix[rowIndex][columnIndex] = tmp;
}
}
return matrix;
}