This solution stores the data as an array of arrays and then uses a recursive function to deliver the solution.
#!/usr/bin/perl
use warnings;
use strict;
# read data into an array of arrays.
my @AoA = ();
while(<DATA>) {
chomp;
my @data = split /\,/, $_;
push @AoA, [ @data ];
}
# determine the depth of the array.
my $depth = scalar @AoA;
print "Depth = $depth\n";
# use a recursive solution to handle arbitrary depth of the data.
permute ( \@AoA, "", 0 );
sub permute {
my $aref = shift;
my $string = shift;
my $index = shift;
if ( $index >= $depth ) {
print $string, "\n";
return;
}
for (@{$aref->[$index]} ) {
my $newstring = $string . $_;
permute( $aref, $newstring, $index + 1)
}
}
__DATA__
A,B
1,2
C,D,E
C:\Code>perl permute_all.pl
Depth = 3
A1C
A1D
A1E
A2C
A2D
A2E
B1C
B1D
B1E
B2C
B2D
B2E
C:\Code>
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.