develooper Front page | perl.beginners | Postings from February 2012

Re: Can recursion eliminate nested foreach() loops?

Thread Previous | Thread Next
From:
Shawn H Corey
Date:
February 26, 2012 18:53
Subject:
Re: Can recursion eliminate nested foreach() loops?
Message ID:
4F4AF006.1060206@gmail.com
On 12-02-26 09:30 PM, Steve Bertrand wrote:
> 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?

There is no simplify way of doing this. Separate off the first attribute 
and cross-product it with a recursive call to the rest. Like this:

#!/usr/bin/env perl

use strict;
use warnings;

my $attributes =
[
   { type => 'colors',  values => [qw/red green blue/]  },
   { type => 'sizes',   values => [qw/small large/] },
   { type => 'shades',  values => [qw/light dark/] },
];

sub combo {
   my @traits = @_;

   # nothing given, nothing returned
   return if @traits == 0;

   # return the last list
   if( @traits == 1 ){
     return map { [ $_ ] } @{ $traits[0]{values} };
   }

   # get the combos for everything but the first one
   my @combos = combo( @traits[ 1 .. $#traits ] );

   # now combine them
   my @result = ();
   for my $first ( @{ $traits[0]{values} } ){
     for my $rest ( @combos ){
       push @result, [ $first, @$rest ];
     }
   }

   return @result;
}

my @list = combo( @$attributes );

for my $set ( @list ){
   print "@$set\n";
}

__END__

-- 
Just my 0.00000002 million dollars worth,
   Shawn

Programming is as much about organization and communication
as it is about coding.

It's Mutual Aid, not fierce competition, that's the dominate
force of evolution.  Of course, anyone who has worked in
open source already knows this.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About