Created
August 27, 2021 22:27
-
-
Save Taosif7/39c59399c0516d97be0b6945df712305 to your computer and use it in GitHub Desktop.
Transpose a 2D rectangle Dart list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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