there are n arrays a_0, ..., a_n-1, each of l elements. how to write efficient code to iterate all combinations, in which each element is picked from a distinct array. for example, if two arrays are [0, 1] and [3, 4], then the output should be
[0, 3]
[0, 4]
[1, 3]
[1, 4]
You cannot do better than
O(l^n), as nightcracker correctly points out. Here’s one way that you can approach the problem.Make a large array
Awhoseith entry is the arraya_i, i.e.A[i] = a_iNow iterate through all words of length
non the alphabet{0,1,...,l}:Finally, select the entries based on the word by
Sorry for the inconsistencies in the pseudocode, but hopefully you can discern the logic here.
Incidentally, based on the example in the question, I am assuming that the first entry should come from the first array, the second entry from the second array, and so on. If this is not the case, then you can still use the idea above and then permute the entries. However, doing this may lead to repetitions if and only if two of the arrays have a common entry.