Problems › JavaScript › patterns
Turn the floor plan a quarter turn
A layout tool rotates a square plan ninety degrees clockwise so it fits the room the other way round.
- The plan is square.
- The top row becomes the right-hand column, read downwards.
- An empty plan comes back empty.
rotateClockwise(plan: list<list<int>>) → list<list<int>>
Where you start
function rotateClockwise(plan) {
}
Worked examples
| Call | Result |
|---|---|
rotateClockwise([[1,2],[3,4]]) | [[3,1],[4,2]] |
rotateClockwise([[1,2,3],[4,5,6],[7,8,9]]) | [[7,4,1],[8,5,2],[9,6,3]] |
rotateClockwise([[1]]) | [[1]] |
rotateClockwise([]) | [] |
Hint
The cell at row r, column c lands at row c, column (last - r). Building a fresh grid is easier to get right than shuffling in place.
Reference solution in JavaScript
function rotateClockwise(plan) {
const n = plan.length;
const turned = [];
for (let r = 0; r < n; r += 1) {
const row = [];
for (let c = 0; c < n; c += 1) row.push(plan[n - 1 - c][r]);
turned.push(row);
}
return turned;
}