I have to create a function to rotate a two-dimensional matrix of N * N integer elements num times, where if num is positive, the rotation is clockwise, and if not, counterclockwise.
Examples
rotateTransform([
[2, 4],
[0, 0]
], 1) /*➞ [
[0, 2],
[0, 4]
]*/
rotateTransform([
[2, 4],
[0, 0]
], -1) /*➞ [
[4, 0],
[2, 0]
]*/
NOTE: I couldn't even try...
CodePudding user response:
the same problem on edabit, and this was the top solution, IDK why you reposting it here...
function rotateTransform(arr, num) {
if (num > 0)
return rotateTransform(arr.map((_, i) => arr.map(x => x[i]).reverse()), num - 1);
else if (num < 0)
return rotateTransform(arr.map((_, i) => arr.map(x => x[i])).reverse(), num 1);
else
return arr;
}
console.log(rotateTransform([
[2, 4],
[0, 0]
], 1))
console.log(rotateTransform([
[2, 4],
[0, 0]
], -1))
CodePudding user response:
For every possible num you enter there are only 3 other orientations and you can get there with at most 2 transforms:
function rotateTransform(arr, num) {
// turn 90deg clockwise
if (num & 1) arr = arr.reverse().map((_, i) => arr.map(row => row[i]));
// turn 180deg
if (num & 2) arr.reverse().forEach(row => row.reverse());
return arr;
}
for (let num = -10; num < 10; num) {
console.log("num", num);
console.log(rotateTransform([
[2, 4],
[0, 0]
], num).join("\n"))
}
.as-console-wrapper{top:0;max-height:100%!important}
