Drill

ProblemsC# › patterns

Turn the rows into columns

easypatternsGridsArraysC#

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

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.

Solve it in Python →

Where you start

public List<List<int>> Transpose(List<List<int>> table) {
    
}

Worked examples

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

The same problem in another language

More patterns problems in C#