0

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?

trejder
  • 17,148
  • 27
  • 124
  • 216
  • 4
    Word on the street is that you can't get away from the complexity of the product (see for instance http://stackoverflow.com/a/1741391/488796). There are ways to speed things up, but more information is needed. How large is "large"? Is your code in the lines of a script, or is it in a `proc` that you are calling (this matters for bytecoding)? – Peter Lewerin Nov 13 '14 at 07:55

1 Answers1

1

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
wolfhammer
  • 2,641
  • 1
  • 12
  • 11