Last active
September 28, 2020 03:15
-
-
Save leodabus/9e627961248835797d67a318bfed0de3 to your computer and use it in GitHub Desktop.
Dictionary Permutations of Collection Value elements
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
// Folow up on Vacawama post on StackOverflow post https://stackoverflow.com/questions/64094640/every-value-combination-of-dictionary/64094971?noredirect=1#comment113341385_64094971 | |
extension Dictionary where Value: Collection { | |
func permutations() -> [[Key: Value.Element]] { | |
guard !isEmpty else { return [] } | |
var permutations: [[Key: Value.Element]] = [] | |
permutate(&permutations) | |
return permutations | |
} | |
private func permutate(_ permutations: inout [[Key: Value.Element]], _ dictionaries: [[Key: Value.Element]] = []) { | |
if let (key, value) = first { | |
var dictionary = self | |
dictionary[key] = nil | |
for element in value { | |
var dictionaries = dictionaries | |
if dictionaries.isEmpty { | |
dictionaries = [[key: element]] | |
} else { | |
for index in dictionaries.indices { | |
dictionaries[index][key] = element | |
} | |
} | |
dictionary.permutate(&permutations, dictionaries) | |
} | |
} else { | |
permutations += dictionaries | |
} | |
} | |
} | |
// *** | |
let dic = ["A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]] | |
let result = dic.permutations() | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment