Skip to content

Instantly share code, notes, and snippets.

@vicneanschi
Created March 15, 2016 23:32
Show Gist options
  • Save vicneanschi/0bf782ea912a412671e6 to your computer and use it in GitHub Desktop.
Save vicneanschi/0bf782ea912a412671e6 to your computer and use it in GitHub Desktop.
Rotate the matrix anti-clockwise
/*
https://www.hackerrank.com/challenges/matrix-rotation-algo
You are given a 2D matrix, a, of dimension MxN and a positive integer R.
You have to rotate the matrix R times and print the resultant matrix.
Rotation should be in anti-clockwise direction.
*/
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
var lines = [];
lineNo = 0;
process.stdin.on("end", function () {
lines = _input.split('\n');
solution();
});
function readLine(){
return lines[lineNo++];
}
function solution(){
var line = readLine();
var tmp = line.split(' ');
var M = tmp[0];
var N = tmp[1];
var R = tmp[2];
var matrix = [];
for (var i = 0; i < M; i++){
line = readLine();
matrix.push(line.split(' '));
}
rotate(matrix, M, N, R);
print(matrix);
}
function print(matrix){
for(var i=0; i< matrix.length; i++)
console.log(matrix[i].join(' '));
}
// rotate the matrix anti-clockwise R times
function rotate(matrix, M, N, R) {
// calculate how many circles we need to rotate
var circles = ~~(Math.min(M, N) / 2);
for(var i = 0; i < circles; i++){
// eliminate unnecessary full circle rotations
var circleLen = (M - i*2)*2 + (N - i*2 - 2)*2;
var rotations = R % circleLen;
for (var j = 0; j < rotations; j++)
{
rotateCircle(matrix, i, i);
}
}
}
//[i,j] [i, n-1-j]
//[m-1-i, j] [m-1-i, n-1-j]
//
function rotateCircle(matrix, i, j){
var k, l;
var m = matrix.length;
var n = matrix[0].length;
var tmp = matrix[i][j];
for ( k = j+1; k <= n-1-j; k++ ){
matrix[i][k-1] = matrix[i][k];
}
for ( k = i+1; k<= m-1-i; k++ ){
//console.log('%s->%s', matrix[k][n-1-j], matrix[k-1][n-1-j])
matrix[k-1][n-1-j] = matrix[k][n-1-j];
}
for ( k = n-1-j; k>j; k-- ) {
//console.log('%s->%s', matrix[m-1-i][k-1], matrix[m-1-i][k])
matrix[m-1-i][k] = matrix[m-1-i][k-1];
}
for ( k = m-1-i; k>i; k-- ) {
matrix[k][j] = matrix[k-1][j];
}
matrix[i+1][j] = tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment