Skip to content

Instantly share code, notes, and snippets.

@alexbinary
Created July 5, 2021 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbinary/e7cfc87f1f31275741594f342df47c49 to your computer and use it in GitHub Desktop.
Save alexbinary/e7cfc87f1f31275741594f342df47c49 to your computer and use it in GitHub Desktop.
Get all possible combinations of the elements in a set
enum Combinatorics {
public static func combinations<T>(of set: Set<T>) -> Set<Set<T>> {
if set.count == 1 {
return Set<Set<T>>([set])
} else {
var allCombinations = Set<Set<T>>()
var diminishedSet = set
let firstItem = diminishedSet.removeFirst()
for combinationOfDiminishedSet in combinations(of: diminishedSet) {
allCombinations.insert(
Set<T>([firstItem])
)
allCombinations.insert(
combinationOfDiminishedSet.union(Set<T>([firstItem]))
)
allCombinations.insert(
combinationOfDiminishedSet
)
}
return allCombinations
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment