how to get the cartesian product of two sets in swift

Here's an algorithm to generate the cartesian product of two sets in Swift using iteration:

main.swift
func cartesianProduct<T>(_ a: Set<T>, _ b: Set<T>) -> Set<Set<T>> {
    var result = Set<Set<T>>()
    for aElement in a {
        for bElement in b {
            result.insert([aElement, bElement])
        }
    }
    return result
}
235 chars
10 lines

You can call the function like this:

main.swift
let a = Set(["a", "b", "c"])
let b = Set([1, 2])
let result = cartesianProduct(a, b)
print(result) // Output: [[“a”, 1], [“a”, 2], [“b”, 1], [“b”, 2], [“c”, 1], [“c”, 2]]
171 chars
5 lines

The output is a set of sets where each inner set represents a cartesian product of elements from set a and set b.

gistlibby LogSnag