Here's one way to get the power set of a set in Swift using recursion and binary representation:
main.swift756 chars20 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.swift138 chars5 lines
gistlibby LogSnag