Turn the rows into columns
An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.
- Every row has the same length.
- The value at row r, column c ends up at row c, column r.
- An empty grid comes back empty.
transpose(table: 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>> transpose(List<List<Integer>> table) {
}
Worked examples
| Call | Result |
|---|---|
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6))) | Main.<List<Integer>>ls(Main.<Integer>ls(1, 4), Main.<Integer>ls(2, 5), Main.<Integer>ls(3, 6)) |
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1))) | Main.<List<Integer>>ls(Main.<Integer>ls(1)) |
transpose(Main.<List<Integer>>ls()) | Main.<List<Integer>>ls() |
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4))) | Main.<List<Integer>>ls(Main.<Integer>ls(1, 3), Main.<Integer>ls(2, 4)) |
Hint
The result has one row per original column. Walk the columns on the outside and the rows on the inside.
Reference solution in Java
List<List<Integer>> transpose(List<List<Integer>> table) {
List<List<Integer>> flipped = new ArrayList<>();
if (table.isEmpty()) return flipped;
for (int c = 0; c < table.get(0).size(); c++) {
List<Integer> row = new ArrayList<>();
for (int r = 0; r < table.size(); r++) row.add(table.get(r).get(c));
flipped.add(row);
}
return flipped;
}