Drill

ProblemsJava › data

Read a grid by columns

easydataGridsArraysJava

A matrix is stored row by row, but a transpose report reads it column by column.

columnMajor(grid: list<list<int>>) → 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<Integer> columnMajor(List<List<Integer>> grid) {
    
}

Worked examples

CallResult
columnMajor(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4)))Main.<Integer>ls(1, 3, 2, 4)
columnMajor(Main.<List<Integer>>ls(Main.<Integer>ls(1), Main.<Integer>ls(2, 3)))Main.<Integer>ls(1, 2, 3)
columnMajor(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6)))Main.<Integer>ls(1, 4, 2, 5, 3, 6)
columnMajor(Main.<List<Integer>>ls(Main.<Integer>ls(5), Main.<Integer>ls(6), Main.<Integer>ls(7)))Main.<Integer>ls(5, 6, 7)

Hint

For each column position, walk every row and take the value when that row is long enough.

Reference solution in Java
List<Integer> columnMajor(List<List<Integer>> grid) {
    List<Integer> result = new ArrayList<>();
    int cols = 0;
    for (List<Integer> row : grid) if (row.size() > cols) cols = row.size();
    for (int c = 0; c < cols; c++) {
        for (List<Integer> row : grid) if (c < row.size()) result.add(row.get(c));
    }
    return result;
}

The same problem in another language

More data problems in Java