transpose method

List<List<T>> transpose()

Transposes a List<List<T>> (rows become columns).

[[1,2,3],[4,5,6]].transpose() // [[1,4],[2,5],[3,6]]

Implementation

List<List<T>> transpose() {
  if (this is! List<List<T>>) {
    throw UnsupportedError('transpose requires a List<List<T>>');
  }
  final matrix = this as List<List<T>>;
  if (matrix.isEmpty || matrix.first.isEmpty) return [];
  final rows = matrix.length;
  final cols = matrix.first.length;
  return List.generate(
    cols,
    (c) => List.generate(rows, (r) => matrix[r][c]),
  );
}