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>>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
List<List<Integer>> rotateClockwise(List<List<Integer>> plan) {
}
Worked examples
| Call | Result |
|---|---|
rotateClockwise(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4))) | Main.<List<Integer>>ls(Main.<Integer>ls(3, 1), Main.<Integer>ls(4, 2)) |
rotateClockwise(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6), Main.<Integer>ls(7, 8, 9))) | Main.<List<Integer>>ls(Main.<Integer>ls(7, 4, 1), Main.<Integer>ls(8, 5, 2), Main.<Integer>ls(9, 6, 3)) |
rotateClockwise(Main.<List<Integer>>ls(Main.<Integer>ls(1))) | Main.<List<Integer>>ls(Main.<Integer>ls(1)) |
rotateClockwise(Main.<List<Integer>>ls()) | Main.<List<Integer>>ls() |
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 Java
List<List<Integer>> rotateClockwise(List<List<Integer>> plan) {
int n = plan.size();
List<List<Integer>> turned = new ArrayList<>();
for (int r = 0; r < n; r++) {
List<Integer> row = new ArrayList<>();
for (int c = 0; c < n; c++) row.add(plan.get(n - 1 - c).get(r));
turned.add(row);
}
return turned;
}