I have n
lists, for example:
L_1 = [a_11, a_12, ...]
L_2 = [a_21, a_22, ...]
...
L_n = [a_n1, a_n2, ...]
where i
th list has k_i
elements.
And now, I want to generate all n
-elements list, where i
th element is from L_i
, I mean:
[a_11, a_21, ..., a_n1]
[a_11, a_21, ..., a_n2]
...
[a_11, a_22, ..., a_n1]
[a_11, a_22, ..., a_n2]
...
[a_12, a_21, ..., a_n1]
[a_12, a_21, ..., a_n2]
...
[a_12, a_22, ..., a_n1]
[a_12, a_22, ..., a_n2]
...
The total number of lists shoulbe be equal to k_1*k_2*...k_n
. Could you describe pseudo-code of this algorithm or use Java code? I can do this using nested for-loops when number of lists is hardcoded, but I'm completely blocked when n
is customizable at runtime.
As you have already found out yourself, the usual trick is to think of the lists a non-uniform version of the g-adic numbers and do carry increment on the list index positions:
When you have
n
lists, you haven
index positions in those lists:The trick is now as follows:
index_pos = [0, 0, ...]
index_pos[0]
.lists[0].size()
, setindex_pos[0] = 0
and incrementindex_pos[1]
.index_pos[1]
is larger than or equal tolists[1].size()
... and so onindex_pos[n - 1]
overflowsAn non-recursive solution in Java would be like
Usage example:
Ok, I implemented this algorithm.
Test class:
Output: