Skip to content

Instantly share code, notes, and snippets.

@Taosif7
Created August 27, 2021 22:27
Show Gist options
  • Save Taosif7/39c59399c0516d97be0b6945df712305 to your computer and use it in GitHub Desktop.
Save Taosif7/39c59399c0516d97be0b6945df712305 to your computer and use it in GitHub Desktop.
Transpose a 2D rectangle Dart list
List<List<R>> transposeList<R>(List<List<R>> input) {
List<List<R>> output = [];
// Check for rectangle matrix
if (input.any((element) => element.length != input[0].length)) {
throw FormatException('Not a rectangle Matrix');
}
for (int i = 0; i < input[0].length; i++) {
output.add(List<R>.generate(input.length, (idx) => null));
}
for (int i = 0; i < input.length; i++) {
List<R> column = input[i];
for (int j = 0; j < input[0].length; j++) {
R rowItem = column[j];
output.elementAt(j).removeAt(i);
output.elementAt(j).insert(i, rowItem);
}
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment