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