Skip to content

Instantly share code, notes, and snippets.

@theachoem
Last active June 1, 2022 07:40
Show Gist options
  • Save theachoem/46bf7ab031b9861b7ab30da7c644f9bc to your computer and use it in GitHub Desktop.
Save theachoem/46bf7ab031b9861b7ab30da7c644f9bc to your computer and use it in GitHub Desktop.
// ignore_for_file: avoid_print
// Input: [[1, 2], [3, 4]]
// Desired output: [3,1, 3,2, 4,1, 4,2]
void main() {
List<List<int>> nestedArray = [
[1, 2],
[3, 4],
[5],
];
print("\nINPUT: $nestedArray");
// #1. Convert from nested array to map
Map nestedMap = nestedArrToMap(nestedArray);
print("\n#1 CONVERTED TO MAP:");
print(nestedMap);
// #2. Extract nested key from map which is expected result
List<String> keys = getNestedKeys(nestedMap);
print("\n#2 MAP TO KEYS:");
print(keys);
print("\nRESULT IN LIST:");
print(keys.map((e) => e.split(",")));
print("");
}
/// Input: [[1, 2], [3, 4]]
/// Output:
/// {
/// 3: {
/// 1: {},
/// 2: {}
/// },
/// 4: {
/// 1: {},
/// 2: {}
/// }
/// }
Map nestedArrToMap(List<List<int>> nestedArray) {
Map nestedMap = {};
int? currentStart;
for (int i = 0; i < nestedArray.length; i++) {
List<int> array = nestedArray[i];
for (int j = 0; j < array.length; j++) {
String element = nestedArray[i][j].toString();
if (currentStart == i) {
nestedMap[element] = {...nestedMap}.values.first;
} else {
currentStart = i;
// set previous map to new map of one element
Map tmpNestedMap = {};
tmpNestedMap[element] = {...nestedMap};
nestedMap = tmpNestedMap;
}
}
}
return nestedMap;
}
// Reference: https://stackoverflow.com/a/56930729/13989964
//
/// Input:
/// {
/// 3: {
/// 1: {},
/// 2: {}
/// },
/// 4: {
/// 1: {},
/// 2: {}
/// }
/// }
///
/// Output: [3,1, 3,2, 4,1, 4,2]
List<String> getNestedKeys(dynamic object, [String? prevKey, List<String> keys = const []]) {
if (object is Map && object.isNotEmpty) {
List<String> newKeys = [];
object.forEach((key, value) {
String newKey = key;
if (prevKey != null) newKey = "$prevKey,$key";
final privatedKeys = getNestedKeys(value, newKey, []);
newKeys.addAll(privatedKeys);
});
return newKeys;
} else {
if (prevKey != null) keys.add(prevKey);
return keys;
}
}
@theachoem
Copy link
Author

theachoem commented May 29, 2022

OUTPUT:

INPUT: [[1, 2], [3, 4], [5]]

#1 CONVERTED TO MAP:
{5: {3: {1: {}, 2: {}}, 4: {1: {}, 2: {}}}}

#2 MAP TO KEYS:
[5,3,1, 5,3,2, 5,4,1, 5,4,2]

RESULT IN LIST:
([5, 3, 1], [5, 3, 2], [5, 4, 1], [5, 4, 2])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment