Question: Given `x` number of arrays, each with a possibly different number of elements, how can I iterate through all combinations where I select one item from each array?

Example:

```
[   ]   [   ]   [   ]
 foo     cat      1
 bar     dog      2
 baz              3
                  4

```

Returns

```
[foo]   [cat]   [ 1 ]
[foo]   [cat]   [ 2 ]
  ...
[baz]   [dog]   [ 4 ]

```

I'm doing this in Perl, btw.

Answer: 
You can use nested loops.

```
for my $e1 (qw( foo bar baz )) {
for my $e2 (qw( cat dog )) {
for my $e3 (qw( 1 2 3 4 )) {
   my @choice = ($e1, $e2, $e3); 
   ...
}}}

```

When you need an arbitrary number of nested loops, you can use [Algorithm::Loops](http://search.cpan.org/perldoc?Algorithm::Loops)'s `NestedLoops`.

```
use Algorithm::Loops qw( NestedLoops );

my @lists = (
   [qw( foo bar baz )],
   [qw( cat dog )],
   [qw( 1 2 3 4 )],
);

my $iter = NestedLoops(\@lists);
while ( my @choice = $iter->() ) {
   ...
}

```
There's one method I thought of first that uses a couple for loops and no recursion.

1. find total number of permutations
2. loop from 0 to total\_permutations-1
3. observe that, by taking the loop index modulus the number of elements in an array, you can get every permutations

Example:

Given A[3], B[2], C[3],

```
for (index = 0..totalpermutations) {
    print A[index % 3];
    print B[(index / 3) % 2];
    print C[(index / 6) % 3];
}

```

where of course a for loop can be substituted to loop over [A B C ...], and a small part can be memoized. Of course, recursion is neater, but this might be useful for languages in which recursion is severely limited by stack size.