This question asks how to compute the Cartesian product of a given number of vectors. Since the number of vectors is known in advance and rather small, the solution is easily obtained with nested for loops.
Now suppose that you are given, in your language of choice, a vector of vectors (or list of lists, or set of sets, etc.):
l = [ [1,2,3], [4,5], [6,7], [8,9,10], [11,12], [13] ]
If I was asked to compute its Cartesian product, that is
[ [1,4,6,8,11,13], [1,4,6,8,12,13], [1,4,6,9,11,13], [1,4,6,9,12,13], ... ]
I would proceed with recursion. For example, in quick&dirty python,
def cartesianProduct(aListOfLists):
if not aListOfLists:
yield []
else:
for item in aListOfLists[0]:
for product in cartesianProduct(aListOfLists[1:]):
yield [item] + product
Is there an easy way to compute it iteratively?
(Note: The answer doesn't need to be in python, and anyway I'm aware that in python itertools does the job better, as in this question.)
Question&Answers:
os