Problems › JavaScript › data
Read a grid by columns
A matrix is stored row by row, but a transpose report reads it column by column.
- Read columns from left to right, and within a column top to bottom.
- A ragged row contributes only the columns it actually has.
columnMajor(grid: list<list<int>>) → list<int>
Where you start
function columnMajor(grid) {
}
Worked examples
| Call | Result |
|---|---|
columnMajor([[1,2],[3,4]]) | [1,3,2,4] |
columnMajor([[1],[2,3]]) | [1,2,3] |
columnMajor([[1,2,3],[4,5,6]]) | [1,4,2,5,3,6] |
columnMajor([[5],[6],[7]]) | [5,6,7] |
Hint
For each column position, walk every row and take the value when that row is long enough.
Reference solution in JavaScript
function columnMajor(grid) {
let cols = 0;
for (const row of grid) if (row.length > cols) cols = row.length;
const result = [];
for (let c = 0; c < cols; c++) {
for (let r = 0; r < grid.length; r++) {
if (c < grid[r].length) result.push(grid[r][c]);
}
}
return result;
}