Approaching in a logical way, You can think this is a combinatory problem. You need to combine each index of each array with each other.
So if you have 3 arrays with 1, 2 and 3 elements you have 6 permutations of 3 elements each. In this case you need to generate 000, 001, 002, 010, 011 and 012.
To achieve this list you can iterate over total combinations incrementing the index of the array that hasnt reach its maximum order, and when it does you reset the index to "0" and increment the next (or previous depending the way you implement it) that hasnt reach it max everytime.
In code:
`#!/usr/bin/perl -w
use strict;
my @array = ([ "a", "b", "c", ],
[ "1", "2", "3", "4", ],
[ "x", "y", ],
[ "U", "V", "W", "X", "Y", "Z",],);
my (@current, @result); # In @current we store the array index to cons
+truct the string
my $comb = 1;
map($comb *= @{$_}, @array); # Get total permutations
for (my $num = 1; $num <= $comb; $num++)
{
my $string = '';
for (my $k = 0; $k <= $#array; $k++)
{
$current[$k] = 0 if !$current[$k];
$string .= ${$array[$k]}[$current[$k]];
}
if ($current[$#array] < $#{$array[$#array]})
{
$current[$#array]++;
}
else #If we reach max index we increment previous not maxed one
{
$current[$#array] = 0;
for (my $i = $#array-1; $i > -1; $i--)
{
# We exit the loop when we increment a not maxed index
$current[$i] < $#{$array[$i]} ? do {$current[$i]++; last} : do {
+$current[$i] = 0};
}
}
push(@result, $string);
}
print join(",", @result) . "\n";
`
The execution:
`[raraya@tolkien perl]$ aoa.pl
a1xU,a1xV,a1xW,a1xX,a1xY,a1xZ,a1yU,a1yV,a1yW,a1yX,a1yY,a1yZ,a2xU,a2xV,
+a2xW,a2xX,a2xY,a2xZ,a2yU,a2yV,a2yW,a2yX,a2yY,a2yZ,a3xU,a3xV,a3xW,a3xX
+,a3xY,a3xZ,a3yU,a3yV,a3yW,a3yX,a3yY,a3yZ,a4xU,a4xV,a4xW,a4xX,a4xY,a4x
+Z,a4yU,a4yV,a4yW,a4yX,a4yY,a4yZ,b1xU,b1xV,b1xW,b1xX,b1xY,b1xZ,b1yU,b1
+yV,b1yW,b1yX,b1yY,b1yZ,b2xU,b2xV,b2xW,b2xX,b2xY,b2xZ,b2yU,b2yV,b2yW,b
+2yX,b2yY,b2yZ,b3xU,b3xV,b3xW,b3xX,b3xY,b3xZ,b3yU,b3yV,b3yW,b3yX,b3yY,
+b3yZ,b4xU,b4xV,b4xW,b4xX,b4xY,b4xZ,b4yU,b4yV,b4yW,b4yX,b4yY,b4yZ,c1xU
+,c1xV,c1xW,c1xX,c1xY,c1xZ,c1yU,c1yV,c1yW,c1yX,c1yY,c1yZ,c2xU,c2xV,c2x
+W,c2xX,c2xY,c2xZ,c2yU,c2yV,c2yW,c2yX,c2yY,c2yZ,c3xU,c3xV,c3xW,c3xX,c3
+xY,c3xZ,c3yU,c3yV,c3yW,c3yX,c3yY,c3yZ,c4xU,c4xV,c4xW,c4xX,c4xY,c4xZ,c
+4yU,c4yV,c4yW,c4yX,c4yY,c4yZ
`
Greetings Rod. |
Comment onGenerating all possible combinations from an AoASelectorDownloadCode