Created
July 5, 2021 07:42
-
-
Save alexbinary/e7cfc87f1f31275741594f342df47c49 to your computer and use it in GitHub Desktop.
Get all possible combinations of the elements in a set
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
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