One way to get distinct combinations of a set in Swift is by using the power set algorithm. Here is the code:
main.swift1503 chars55 lines
The powerSet
function returns all possible subsets of a set. Then, the getCombinations
function uses these subsets to generate all possible combinations of the set with a given size. Finally, the getDistinctCombinations
function removes duplicates by checking if a combination is a permutation of another (i.e. both have the same elements but in a different order).
You can call the getDistinctCombinations
function with a set and the desired size of the combinations to get a set of distinct combinations. For example:
main.swift189 chars6 lines
gistlibby LogSnag