I came across a question early this morning on a forum that intrigued
me. I literally spent about five hours trying everything to solve it,
but I couldn't.
Every attempt at recursion, counting, numbering, hashing etc failed. Is
there a way to use recursion to eliminate the repeated and
pre-calculated calls to foreach as this OP is asking?
From ... .. ... is verbatim 'dms000'
...
I need to generate a list of combinations from a data structure such as:
my $attributes =
[
{ type => 'colors', values => [qw/red green blue/] },
{ type => 'sizes', values => [qw/small large/] },
{ type => 'shades', values => [qw/light dark/] },
];
It is easy enough when the number of "types" are known:
my @combos = ();
foreach my $a (@{$attributes->[0]->{values}}) {
foreach my $b (@{$attributes->[1]->{values}}) {
foreach my $c (@{$attributes->[2]->{values}}) {
push @combos, [$a, $b, $c];
}
}
}
Which results in a list such as:
red small light
red small dark
red large light
red large dark
green small light
...
But how to do with arbitrary number of types? Obviously will need
recursion but I can't figure it out. The only thing I could come up with
was generating code like code2 as a string and eval()ing it...a poor
solution.
...
I know this isn't a beginner's question, but I know there are geniuses
here. Is there a way to simplify this within Perl?
Steve
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/