Cartesian Product with Higher Order Functions
Every now and then you get a number of lists, and you have to compute the cartesian product of these lists. Say, you have three lists:
L1 | L2 | L3 |
---|---|---|
a | x | 1 |
b | y | 2 |
z |
and you want to have:
[ [a,x,1], [a,x,2], [a,y,1], [a,y,2], [a,z,1], [a,z,2],
[b,x,1], [b,x,2], [b,y,1], [b,y,2], [b,z,1], [b,z,2] ]
One way of doing this is using a slice of indexes, in this case, a slice of 3, containing the index for each list. Something like this:
// ctr is declared as ctr:=make([]int,len(lists))
carry := false
for i := range ctr {
ctr[i]++
if ctr[i] >= len(lists[i]) {
ctr[i] = 0
carry = true
continue
}
carry = false
break
}
Every time you run this code, it increments ctr
, and you can
construct the result by selecting lists[i][ctr[i]]
for every list.
This gets a bit tricky if you are joining multiple interdependent
queries, because then the lists are not static: You get a list L2
when processing ‘a’, and then another instance of ``L2when processing
b. Then, when processing
aand
xyou get an instance of
L3, and another instance for
a,
y`, etc.