Created
August 28, 2022 16:23
-
-
Save Deityhub/00c1a72255052d3a04d8f20511917c03 to your computer and use it in GitHub Desktop.
Rotate 2D array matrix to the left (one step at a time)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function rotateMatrix(rowCount, colCount, matrix) { | |
let row = 0; | |
let col = 0; | |
let prev; | |
let curr; | |
/* | |
row - Starting row index | |
rowCount - ending row index | |
col - starting column index | |
colCount - ending column index | |
i - iterator | |
*/ | |
while (row < rowCount && col < colCount) { | |
if (row + 1 === rowCount || col + 1 === colCount) break; | |
// Store the first element of next | |
// row, this element will replace | |
// first element of current row | |
// prev = matrix[row + 1][col]; | |
prev = matrix[row + 1][colCount - 1]; | |
// Move elements of first row | |
// from the remaining rows | |
for (let i = colCount - 1; i >= col; i--) { | |
curr = matrix[row][i]; | |
matrix[row][i] = prev; | |
prev = curr; | |
} | |
row++; | |
// Move elements of first column | |
// from the remaining columns | |
for (let i = row; i < rowCount; i++) { | |
curr = matrix[i][col]; | |
matrix[i][col] = prev; | |
prev = curr; | |
} | |
col++; | |
// Move elements of last row | |
// from the remaining rows | |
if (row < rowCount) { | |
for (let i = col; i < colCount; i++) { | |
curr = matrix[rowCount - 1][i]; | |
matrix[rowCount - 1][i] = prev; | |
prev = curr; | |
} | |
} | |
rowCount--; | |
// Move elements of last column | |
// from the remaining rows | |
if (col < colCount) { | |
for (let i = rowCount - 1; i >= row; i--) { | |
curr = matrix[i][colCount - 1]; | |
matrix[i][colCount - 1] = prev; | |
prev = curr; | |
} | |
} | |
colCount--; | |
} | |
return matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment