Print Cartesian product of two list, without nested foreach

170 views Asked by At

I need to calculate a Cartesian product of two lists.

My list contains large number of elements, so nested foreach is not a good idea in my case.

Anything else, that can be used there?

1

There are 1 answers

0
wolfhammer On

You might be able to work on the values while it's being put together. It's hard to say without at least a snapshot of the structure you're working with. Here's a simple example.

The proc doesn't return a matrix it does work on points in the matrix.

proc my_cartesian {a b} {

    set len_a [llength $a]
    set len_b [llength $b]
    set len [expr $len_a * $len_b]
    set y 0
    for {set i 0} {$i < $len} {incr i} {
        set x [expr $i % $len_a]
        if {$x == 0 && $i != 0} {
            incr y
        }
        set px [lindex $a $x]
        set py [lindex $b $y]

        # Your code
        puts "$px, $py"
    }

}

my_cartesian {a b c} {1 2 3}

output:

a, 1
b, 1
c, 1
a, 2
b, 2
c, 2
a, 3
b, 3
c, 3