I needed to rotate a non-square matrix in my program to transpose some spreadsheet data and decided to make a function to rotate 90, 180, or 270 degrees.
It doesn't rotate the matrix in place, but instead generates a copy and returns that. I want to go for processing efficiency, let me know what I can do better:
//Rotates the provided matrix by provided degrees counterclockwise
function RotateMatrix(matrix, degrees){
if(degrees == 90){
//For 90 degrees swap the height/width and swap the location of each element
var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
for(var i = 0; i < matrix[0].length; i++){
for(var j = 0; j < matrix.length; j++){
output[i][j] = matrix[j][i];
}
}
} else if(degrees == 180) {
//For 180 degrees, rebuild array backwards
var output = GenerateMatrix(matrix.length, matrix[0].length, 0);
for(var i = matrix.length - 1; i >= 0; i--){
for(var j = matrix[0].length - 1; j >=0; j--){
output[matrix.length - 1 - i][matrix[0].length - 1 - j] = matrix[i][j];
}
}
} else if(degrees == 270) {
//For 270 degrees, not sure how to make short description
var output = GenerateMatrix(matrix[0].length, matrix.length, 0); //Swapping the width and height for non square matrices
for(var i = 0; i < matrix[0].length; i++){
for(var j = matrix.length - 1; j >=0; j--){
output[i][matrix.length - 1 - j] = matrix[j][i];
}
}
}
return output;
}
//Generates a matrix with the requested length and width and value
function GenerateMatrix(length, width, value){
var output = [];
for(var i = 0; i < length; i++){
width > 0 ? output.push([]) : output.push(value); //If matrix has 0 width
for(var j = 0; j < width; j++){
output[i].push(value)
}
}
return output;
}