Drill

ProblemsTypeScript › patterns

Turn the floor plan a quarter turn

mediumpatternsGridsArraysTypeScript

A layout tool rotates a square plan ninety degrees clockwise so it fits the room the other way round.

rotateClockwise(plan: list<list<int>>) → list<list<int>>

Solve it in the editor →

Where you start

function rotateClockwise(plan: number[][]): number[][] {
  
}

Worked examples

CallResult
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 TypeScript
function rotateClockwise(plan: number[][]): number[][] {
  const n = plan.length;
  const turned: number[][] = [];
  for (let r = 0; r < n; r += 1) {
    const row: number[] = [];
    for (let c = 0; c < n; c += 1) row.push(plan[n - 1 - c][r]);
    turned.push(row);
  }
  return turned;
}

The same problem in another language

More patterns problems in TypeScript