Rotating matrix in-place

by Anton Bagayev

HTML

<p id="output"></p>

JavaScript

function rotateMatrix(mat, clockwise) {
  let N = mat.length;
  let tmp;
  if (clockwise) {
  	for (let i = 0; i < N/2; i++) {
      for (let j = i; j < N-1-i; j++) {
        tmp = mat[i][j]; 
        // move values from left to top 
        mat[i][j] = mat[N-1-j][i]; 
        // move values from bottom to left 
        mat[N-1-j][i] = mat[N-1-i][N-1-j]; 
        // move values from right to bottom 
        mat[N-1-i][N-1-j] = mat[j][N-1-i]; 
        // assign temp to right 
        mat[j][N-1-i] = tmp; 
      }
    }
  } else {
  	for (let i = 0; i < N/2; i++) {
      for (let j = i; j < N-1-i; j++) {
        tmp = mat[i][j]; 
        // move values from right to top 
        mat[i][j] = mat[j][N-1-i]; 
        // move values from bottom to right 
        mat[j][N-1-i] = mat[N-1-i][N-1-j]; 
        // move values from left to bottom 
        mat[N-1-i][N-1-j] = mat[N-1-j][i]; 
        // assign temp to left 
        mat[N-1-j][i] = tmp; 
      }
    }
  }
  return mat;
}

function createMatrix(size){
	let result = [];
  let counter = 1;
  for (let i = 0; i < size; i++) {
  	let row = [];
  	for (let j = 0; j < size; j++) {
      row.push(counter);
      counter++;
    }
    result.push(row);
  }
  return result;
}

function printMatrix(mat) {
	let result = "";
	for (let i = 0; i < mat.length; i++) {
  	for (let j = 0; j < mat[i].length; j++) {
    	result += mat[i][j] + " ";
    }
    result += "<br>";
  }
  return result;
}

let input = createMatrix(4);
let result = rotateMatrix(input, true);
document.getElementById("output").innerHTML = printMatrix(result);