Drill

ProblemsC++ › data

Read a grid by columns

easydataGridsArraysC++

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

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

std::vector<int> columnMajor(std::vector<std::vector<int>> grid) {
    
}

Worked examples

CallResult
columnMajor(std::vector<std::vector<int>>{std::vector<int>{1, 2}, std::vector<int>{3, 4}})std::vector<int>{1, 3, 2, 4}
columnMajor(std::vector<std::vector<int>>{std::vector<int>{1}, std::vector<int>{2, 3}})std::vector<int>{1, 2, 3}
columnMajor(std::vector<std::vector<int>>{std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}})std::vector<int>{1, 4, 2, 5, 3, 6}
columnMajor(std::vector<std::vector<int>>{std::vector<int>{5}, std::vector<int>{6}, std::vector<int>{7}})std::vector<int>{5, 6, 7}

Hint

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

Reference solution in C++
std::vector<int> columnMajor(std::vector<std::vector<int>> grid) {
    std::vector<int> result;
    int cols = 0;
    for (const auto& row : grid) if ((int) row.size() > cols) cols = (int) row.size();
    for (int c = 0; c < cols; c++) {
        for (const auto& row : grid) if (c < (int) row.size()) result.push_back(row[c]);
    }
    return result;
}

The same problem in another language

More data problems in C++