Cartesian product of two or more lists

In Sidef, the Cartesian product of an arbitrary number of arrays is built-in as Array.cartesian():

cartesian([[1,2], [3,4], [5,6]]).say
cartesian([[1,2], [3,4], [5,6]], {|*arr| say arr })

Alternatively, a simple recursive implementation:

func cartesian_product(*arr) {

    var c = []
    var r = []

    func {
        if (c.len < arr.len) {
            for item in (arr[c.len]) {
                c.push(item)
                __FUNC__()
                c.pop
            }
        }
        else {
            r.push([c...])
        }
    }()

    return r
}

Completing the task:

Output:

The product of an empty list with any other list is empty:

Output:

Extra credit:

Output:

Output:

Last updated