Drill

ProblemsJava › patterns

Turn the rows into columns

easypatternsGridsArraysJava

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

Java 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

List<List<Integer>> transpose(List<List<Integer>> table) {
    
}

Worked examples

CallResult
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6)))Main.<List<Integer>>ls(Main.<Integer>ls(1, 4), Main.<Integer>ls(2, 5), Main.<Integer>ls(3, 6))
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1)))Main.<List<Integer>>ls(Main.<Integer>ls(1))
transpose(Main.<List<Integer>>ls())Main.<List<Integer>>ls()
transpose(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4)))Main.<List<Integer>>ls(Main.<Integer>ls(1, 3), Main.<Integer>ls(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 Java
List<List<Integer>> transpose(List<List<Integer>> table) {
    List<List<Integer>> flipped = new ArrayList<>();
    if (table.isEmpty()) return flipped;
    for (int c = 0; c < table.get(0).size(); c++) {
        List<Integer> row = new ArrayList<>();
        for (int r = 0; r < table.size(); r++) row.add(table.get(r).get(c));
        flipped.add(row);
    }
    return flipped;
}

The same problem in another language

More patterns problems in Java