how to get the power set of a set in swift

Here's one way to get the power set of a set in Swift using recursion and binary representation:

main.swift
func powerSet<T>(_ set: Set<T>) -> [[T]] {
    let binaryCount = 1 << set.count // calculate the number of binary digits needed
    var powerSet: [[T]] = []
    
    for i in 0..<binaryCount {
        let binary = String(i, radix: 2) // get the binary representation of the current number
        let paddedBinary = binary.padding(toLength: set.count, withPad: "0", startingAt: 0) // pad the binary representation with leading zeros
        let subset = paddedBinary.enumerated().compactMap({ (index, digit) -> T? in
            if digit == "1" {
                return set[set.index(set.startIndex, offsetBy: index)]
            } else {
                return nil
            }
        })
        powerSet.append(subset)
    }
    
    return powerSet
}
756 chars
20 lines

This function first calculates the number of binary digits needed to represent all possible subsets of the input set. It then generates every binary number from 0 to binaryCount-1, pads each number with leading zeros so that it has set.count digits, and converts each digit of the binary number to either an element of the set or nil depending on whether the digit is 1 or 0, respectively. The resulting array of arrays represents the power set of the input set.

You can use this function like so:

main.swift
let set = Set([1, 2, 3])
let powerSet = powerSet(set)

print(powerSet) // prints "[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]"
138 chars
5 lines

gistlibby LogSnag