I need to be able to rotate a 2d array of data both clockwise and counterclockwise (right and left), in 2 separated functions.
I was able to make the first function which does clockwise rotation to work well but I'm having modifying my code for the second function which should turn counterclockwise.
This is my function for clockwise rotation in Typescript:
function rotateClockwise<T>(arr: T[][]) {
const ret: any[][] = arr.map(c => c.map(v => "")); // blank copy
const rows = arr.length;
if (rows === 0) return ret;
const cols = arr[0].length;
if (!arr.every(l => l.length === cols)) throw new Error("Not rectangular");
const stationaryRing = (rows % 2 !== 0) && (cols % 2 !== 0) ? (Math.min(rows, cols) - 1)/2:-1
console.log('stationaryRingx = ', stationaryRing)
for (let r = 0; r < rows; r++) {
let nr = rows - 1 - r;
for (let c = 0; c < cols; c++) {
let nc = cols - 1 - c;
const ring = Math.min(r, nr, c, nc);
let [rNew, cNew] = [r, c];
if (ring !== stationaryRing) {
if (r === ring && nc !== ring) cNew++; // top row moves right (except for rightmost)
else if (c === ring) rNew--; // left column moves up
else if (nr === ring) cNew--; // bottom row moves left
else rNew++; // right column moves down
}
ret[rNew][cNew] = arr[r][c];
}
}
return ret;
}
for the following input table:
1 2 3
4 5 6
7 8 9
The code above produces this table:
4 1 2
7 5 3
8 9 6
I need to change the code in order for it rotate to the left so if I use the same input table above I should get:
2 3 6
1 5 9
4 7 8
I thought that by changing the conditions as described below I would be able to make a counterclockwise rotation but it did not work:
if (ring !== stationaryRing) {
if (r === ring && nc !== 0) rNew-- ; // top row moves left (except for leftmost)
else if (c === ring) rNew++; // left column moves down
else if (nr === ring) cNew++; // bottom row moves right
else cNew--; // right column moves up
}
Any ideas? Thanks!