transpose a 2d array (matrix).

if you're wondering what's the difference between this and transposeArray2D from the "array2d" submodule, then be my guest, because I am just as puzzled as you. perhaps I forgot that I made one or the other, resulting in duplication.

however, there are a few implementation differences between the these two functions:

similarities between the two functions:

  • both transpose sparse 2d arrays to full 2d arrays with the sparse entries replaced with undefined.
  • both use the first element (the first row) to determine the number of columns your 2d array has. this can mean disastrous cropped results if a sparse 2d array is provided where the first row's number of elements (i.e. number of columns) is not the greatest out of all the other rows.
import { assertEquals } from "jsr:@std/assert"

const sparse_arr2d: Array<number[]> = [
[1 , 2 , 3 , 4 , 5 ],
[6 , 7 , 8 , 9],
[11, 12, 13],
[16, 17, 18, 19, 20],
]

const sparse_arr2d_transposed = transpose2D(sparse_arr2d)

sparse_arr2d_transposed satisfies Array<number>[]

assertEquals(sparse_arr2d_transposed, [
[1 , 6 , 11 , 16],
[2 , 7 , 12 , 17],
[3 , 8 , 13 , 18],
[4 , 9 , undefined , 19],
[5 , undefined , undefined , 20],
])