how to get distinct permutations of a set in swift

Here's a recursive solution in Swift to get distinct permutations of a set:

main.swift
func getDistinctPermutations<T>(set: Set<T>) -> Set<Set<T>> {
    if set.count == 1 {
        return Set([set])
    }
    
    var result = Set<Set<T>>()
    
    for element in set {
        var reducedSet = set
        reducedSet.remove(element)
        
        let permutations = getDistinctPermutations(set: reducedSet)
        
        for permutation in permutations {
            result.insert(permutation.union([element]))
        }
    }
    
    return result
}
473 chars
21 lines

Here's how you can use this function:

main.swift
let set = Set(["a", "b", "c"])
let permutations = getDistinctPermutations(set: set)

print(permutations)
// Prints: [[b, c, a], [c, b, a], [b, a, c], [c, a, b], [a, b, c], [a, c, b]]
183 chars
6 lines

This function takes a set as input and returns a set of sets, where each set represents a distinct permutation of the original set. The algorithm works by iterating over each element in the set and recursively getting the distinct permutations of the reduced set (i.e. the original set without the current element). We then combine each permutation with the current element to get all possible permutations that include the current element. Finally, we add all these permutations to the result set.

gistlibby LogSnag