Skip to content

Instantly share code, notes, and snippets.

@Deityhub
Created August 28, 2022 16:23
Show Gist options
  • Select an option

  • Save Deityhub/00c1a72255052d3a04d8f20511917c03 to your computer and use it in GitHub Desktop.

Select an option

Save Deityhub/00c1a72255052d3a04d8f20511917c03 to your computer and use it in GitHub Desktop.

Revisions

  1. Deityhub created this gist Aug 28, 2022.
    66 changes: 66 additions & 0 deletions rotateMatrixToLeft.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    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;
    }