Problems › TypeScript › patterns
Turn the rows into columns
An export writes a table row by row, and the spreadsheet on the other end wants it the other way round.
- Every row has the same length.
- The value at row r, column c ends up at row c, column r.
- An empty grid comes back empty.
transpose(table: list<list<int>>) → list<list<int>>
Where you start
function transpose(table: number[][]): number[][] {
}
Worked examples
| Call | Result |
|---|---|
transpose([[1,2,3],[4,5,6]]) | [[1,4],[2,5],[3,6]] |
transpose([[1]]) | [[1]] |
transpose([]) | [] |
transpose([[1,2],[3,4]]) | [[1,3],[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 TypeScript
function transpose(table: number[][]): number[][] {
if (table.length === 0) return [];
const flipped: number[][] = [];
for (let c = 0; c < table[0].length; c += 1) {
const row: number[] = [];
for (let r = 0; r < table.length; r += 1) row.push(table[r][c]);
flipped.push(row);
}
return flipped;
}