how to get distinct combinations of a set in swift

One way to get distinct combinations of a set in Swift is by using the power set algorithm. Here is the code:

main.swift
func powerSet<T>(_ set: Set<T>) -> Set<Set<T>> {
    let elements = Array(set)
    let count = Int(pow(Double(2), Double(set.count)))
    var result = Set<Set<T>>()
    
    for i in 0..<count {
        var subset = Set<T>()
        for j in 0..<set.count {
            if (i & (1 << j)) != 0 {
                subset.insert(elements[j])
            }
        }
        result.insert(subset)
    }
    
    return result
}

func getCombinations<T>(_ set: Set<T>, r: Int) -> Set<Set<T>> {
    if r == 0 || set.count < r {
        return []
    }
    
    var combinations = Set<Set<T>>()
    let elements = Array(set)
    
    for i in 0...(elements.count - r) {
        let first = elements[i]
        let remaining = Set(elements[(i+1)...])
        let remainingCombinations = getCombinations(remaining, r: r-1)
        for comb in remainingCombinations {
            var subset = Set<T>()
            subset.insert(first)
            subset = subset.union(comb)
            combinations.insert(subset)
        }
    }
    
    return combinations
}

func getDistinctCombinations<T>(_ set: Set<T>, r: Int) -> Set<Set<T>> {
    let allCombinations = getCombinations(set, r: r)
    var distinctCombinations = Set<Set<T>>()
    
    for combination in allCombinations {
        let sortedCombination = Set(combination.sorted())
        if !distinctCombinations.contains(sortedCombination) {
            distinctCombinations.insert(sortedCombination)
        }
    }
    
    return distinctCombinations
}
1503 chars
55 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.swift
let s: Set<Int> = [1, 2, 3, 4]
let r = 2
let distinctCombinations = getDistinctCombinations(s, r: r)
print(distinctCombinations)
// Output: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
189 chars
6 lines

gistlibby LogSnag