get distinct permutations of a set in swift

Here's the code to get distinct permutations of a set in Swift using recursion:

main.swift
func getPermutations<T>(_ set: Set<T>) -> [[T]] {
    var setArray = Array(set)
    var permutations: [[T]] = []

    func heapPermutation(_ n: Int) {
        if n == 1 {
            permutations.append(setArray)
            return
        }

        for i in 0..<n {
            heapPermutation(n - 1)

            if n % 2 == 1 {
                setArray.swapAt(0, n - 1)
            } else {
                setArray.swapAt(i, n - 1)
            }
        }
    }

    heapPermutation(set.count)
    return permutations
}
525 chars
25 lines

The above function uses Heap's algorithm to generate permutations recursively. The function takes a set as input and returns an array of distinct permutations. The heapPermutation function generates the permutations by swapping elements in the set, and the base case is reached when there is only one element left.

To use this function, simply call getPermutations and pass in a set of elements:

main.swift
let set = Set([1, 2, 3])
let permutations = getPermutations(set)
print(permutations) // Output: [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
163 chars
4 lines

gistlibby LogSnag