how to get all combinations of a set in swift

Here's a recursive function in Swift to get all combinations of a given set of elements:

main.swift
func getCombinations<T>(from elements: [T], choose: Int) -> [[T]] {
    guard choose > 0 else { return [] } // edge case, no elements to choose, return empty array
    guard choose != 1 else { return elements.map { [$0] } } // base case, choose 1 element, return each element as array
    var combinations = [[T]]()
    for (index, element) in elements.enumerated() {
        var reducedElements = elements
        reducedElements.removeFirst(index+1) // get all combinations from remaining elements
        let subCombinations = getCombinations(from: reducedElements, choose: choose - 1)
        for subCombination in subCombinations {
            combinations.append([element] + subCombination) // add the current element with subcombination
        }
    }
    return combinations
}
786 chars
15 lines

This function takes an array of elements and the number of elements to choose (the size of combinations). The function first checks for edge cases - if the choose size is zero, return an empty array, and for the base case where the choose size is one, it returns each element as an array.

For the other cases, the function iterates over each element of the array and uses recursion to get all combinations from the remaining elements with one less choose size. The subcombinations are then concatenated with the current element to get complete combinations.

Here's an example usage:

main.swift
let elements = [1, 2, 3, 4]
let combinations = getCombinations(from: elements, choose: 3)
print(combinations)
// Output: [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
166 chars
5 lines

gistlibby LogSnag