how to get all subsets of a set in swift

To get all subsets of a set, we can use recursion. The idea is to either include an element into the current subset or exclude it. We will start with an empty subset and recursively build all possible subsets.

Here's the code that implements this algorithm:

main.swift
func getSubsets(_ set: [Int]) -> [[Int]] {
    if set.isEmpty {
        return [[]]
    } else {
        let head = set[0]
        let tail = Array(set.dropFirst())
        let subsetWithoutHead = getSubsets(tail)
        let subsetWithHead = subsetWithoutHead.map { [head] + $0 }
        return subsetWithHead + subsetWithoutHead
    }
}
339 chars
12 lines

Let's break down this code a bit. We start by checking if the input set is empty. If so, we return an array containing the empty set. Otherwise, we take the first element of the set as the head and the rest of the set as the tail.

We recursively call getSubsets on the tail, which will return all the subsets of the tail. Then we create a new set of subsets by adding the head to each of those subsets. Finally, we return the union of these two sets of subsets: those without the head and those with the head.

Here's an example usage:

main.swift
let set = [1, 2, 3]
let subsets = getSubsets(set)
print(subsets) // [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
123 chars
4 lines

This code correctly generates all subsets of the set {1, 2, 3}.

gistlibby LogSnag