Code style fixes for matrix rotation algorithm.

This commit is contained in:
Oleksii Trekhleb 2018-07-06 12:02:42 +03:00
parent 57378c5e19
commit bb86b30dda
2 changed files with 18 additions and 9 deletions

View File

@ -92,13 +92,13 @@ A B C
/ / •
/ • •
And not let's do horizontal reflection:
And now let's do horizontal reflection:
A → →
B → →
C → →
The string has been rotated to 90 degree.
The string has been rotated to 90 degree:
• • A
• • B

View File

@ -8,19 +8,28 @@ export default function squareMatrixRotation(originalMatrix) {
// 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;
// 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) {
const mirrorColumnIndex = matrix.length - columnIndex - 1;
const tmp = matrix[rowIndex][mirrorColumnIndex];
matrix[rowIndex][mirrorColumnIndex] = matrix[rowIndex][columnIndex];
matrix[rowIndex][columnIndex] = tmp;
// Swap elements.
[
matrix[rowIndex][matrix.length - columnIndex - 1],
matrix[rowIndex][columnIndex],
] = [
matrix[rowIndex][columnIndex],
matrix[rowIndex][matrix.length - columnIndex - 1],
];
}
}