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>>
C# 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
public List<List<int>> Transpose(List<List<int>> table) {
}
Worked examples
| Call | Result |
|---|---|
Transpose(new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 } }) | new List<List<int>> { new List<int> { 1, 4 }, new List<int> { 2, 5 }, new List<int> { 3, 6 } } |
Transpose(new List<List<int>> { new List<int> { 1 } }) | new List<List<int>> { new List<int> { 1 } } |
Transpose(new List<List<int>> { }) | new List<List<int>> { } |
Transpose(new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } }) | new List<List<int>> { new List<int> { 1, 3 }, new List<int> { 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 C#
public List<List<int>> Transpose(List<List<int>> table) {
var flipped = new List<List<int>>();
if (table.Count == 0) return flipped;
for (int c = 0; c < table[0].Count; c++) {
var row = new List<int>();
for (int r = 0; r < table.Count; r++) row.Add(table[r][c]);
flipped.Add(row);
}
return flipped;
}