Drill

ProblemsGo › patterns

Turn the rows into columns

easypatternsGridsArraysGo

An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.

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.

Solve it in Python →

Where you start

func transpose(table [][]int) [][]int {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More patterns problems in Go