Read a grid by columns
A matrix is stored row by row, but a transpose report reads it column by column.
- Read columns from left to right, and within a column top to bottom.
- A ragged row contributes only the columns it actually has.
ColumnMajor(grid: list<list<int>>) → 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<int> ColumnMajor(List<List<int>> grid) {
}
Worked examples
| Call | Result |
|---|---|
ColumnMajor(new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } }) | new List<int> { 1, 3, 2, 4 } |
ColumnMajor(new List<List<int>> { new List<int> { 1 }, new List<int> { 2, 3 } }) | new List<int> { 1, 2, 3 } |
ColumnMajor(new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 } }) | new List<int> { 1, 4, 2, 5, 3, 6 } |
ColumnMajor(new List<List<int>> { new List<int> { 5 }, new List<int> { 6 }, new List<int> { 7 } }) | new List<int> { 5, 6, 7 } |
Hint
For each column position, walk every row and take the value when that row is long enough.
Reference solution in C#
public List<int> ColumnMajor(List<List<int>> grid) {
var result = new List<int>();
int cols = 0;
foreach (var row in grid) if (row.Count > cols) cols = row.Count;
for (int c = 0; c < cols; c++) {
foreach (var row in grid) if (c < row.Count) result.Add(row[c]);
}
return result;
}