Created
November 1, 2017 19:52
-
-
Save AdrianFerreyra/ec2fa8d8060bf136135f782e12343e10 to your computer and use it in GitHub Desktop.
Getting permutations of a Set of Strings recursively.
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
import Foundation | |
func permutations(_ set: Set<String>) -> Set<String> { | |
guard set.count != 0 else { | |
return Set<String>([""]) | |
} | |
return set.reduce(Set<String>()) { accumulator, element in | |
accumulator.union(permutations(set.subtracting([element])).map { element + $0 } ) | |
} | |
} | |
let set = Set<String>(["a","b","c","d","e"]) | |
print(permutations(set)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incredibly, Swift's flatMap implementation for Sets SUCKS. That's why I have to use this fold instead.