Skip to content

Instantly share code, notes, and snippets.

@petersandor
Last active June 9, 2022 18:45
Show Gist options
  • Save petersandor/15c7365d6a6611b7f589410ed999f166 to your computer and use it in GitHub Desktop.
Save petersandor/15c7365d6a6611b7f589410ed999f166 to your computer and use it in GitHub Desktop.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const rotateMatrix = (inputMatrix: Array<Array<Number>>, rotateBy: number) => {
let outputMatrix = new Array(inputMatrix.length).fill([]);
if (rotateBy === 0) {
return inputMatrix;
}
outputMatrix = outputMatrix.map((row, index) => {
const newRow = [];
for (let counter = 0; counter < inputMatrix.length; counter++) {
newRow.push(inputMatrix[(inputMatrix.length - 1) - counter][index])
}
return newRow;
});
return rotateMatrix(outputMatrix, rotateBy - 90);
}
console.log(rotateMatrix(matrix, 90));
console.log(rotateMatrix(matrix, 180));
console.log(rotateMatrix(matrix, 270));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment