Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 1, 2017 19:52
Show Gist options
  • Save AdrianFerreyra/ec2fa8d8060bf136135f782e12343e10 to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/ec2fa8d8060bf136135f782e12343e10 to your computer and use it in GitHub Desktop.
Getting permutations of a Set of Strings recursively.
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))
@AdrianFerreyra
Copy link
Author

Incredibly, Swift's flatMap implementation for Sets SUCKS. That's why I have to use this fold instead.

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