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>
Go 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
func columnMajor(grid [][]int) []int {
}
Worked examples
| Call | Result |
|---|---|
columnMajor([][]int{[]int{1, 2}, []int{3, 4}}) | []int{1, 3, 2, 4} |
columnMajor([][]int{[]int{1}, []int{2, 3}}) | []int{1, 2, 3} |
columnMajor([][]int{[]int{1, 2, 3}, []int{4, 5, 6}}) | []int{1, 4, 2, 5, 3, 6} |
columnMajor([][]int{[]int{5}, []int{6}, []int{7}}) | []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 Go
func columnMajor(grid [][]int) []int {
cols := 0
for _, row := range grid {
if len(row) > cols {
cols = len(row)
}
}
result := []int{}
for c := 0; c < cols; c++ {
for _, row := range grid {
if c < len(row) {
result = append(result, row[c])
}
}
}
return result
}