Is there a standard library method to compute the cartesian product of two arrays?
I'm currently using this, works well for two arrays, but gets more complicated for more than two:
// Cartesian product of two arrays
func * <U, V>(lhs: [U], rhs: [V]) -> [(U, V)] {
lhs.flatMap { left in
rhs.map { right in
(left, right)
}
}
}
print([1, 2, 3] * ["a", "b"])
// [(1, "a"), (1, "b"), (2, "a"), (2, "b"), (3, "a"), (3, "b")]
I believe both Python and Ruby have functions to generate cartesian products, but not sure if there is anything similar in Swift.