Drill

ProblemsTypeScript › patterns

Turn the rows into columns

easypatternsGridsArraysTypeScript

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

Solve it in the editor →

Where you start

function transpose(table: number[][]): number[][] {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More patterns problems in TypeScript