Skip to content

Instantly share code, notes, and snippets.

@leodabus
Last active September 28, 2020 03:15
Show Gist options
  • Save leodabus/9e627961248835797d67a318bfed0de3 to your computer and use it in GitHub Desktop.
Save leodabus/9e627961248835797d67a318bfed0de3 to your computer and use it in GitHub Desktop.
Dictionary Permutations of Collection Value elements
// 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