perlrocks has asked for the wisdom of the Perl Monks concerning the following question:

hi-

I have a function that receives lists. Lists received are of arbitrary lengths and the number of lists received cannot be known a priori.

I would like to be able to produce all combinations of the lists' elements while preserving the order of the lists. An example follows:

Suppose we have 3 lists:

list 1: (1,2)

list 2: (a,b)

list 3: (#,*,&)

i would like to produce the following:

1,a,#

1,a,*

1,a,&

1,b,#

1,b,*

1,b,&

2,a,#

2,a,*

2,a,&

2,b,#

2,b,*

2,b,&

Replies are listed 'Best First'.
Re: Combinatorics problem
by almut (Canon) on Sep 03, 2009 at 21:51 UTC

    You could try List::Comprehensions

    use List::Comprehensions; local $"=","; print comp1 { "@_\n" } [1,2], [qw(a b)], [qw(# * &)];

    Output:

    1,a,# 1,a,* 1,a,& 1,b,# 1,b,* 1,b,& 2,a,# 2,a,* 2,a,& 2,b,# 2,b,* 2,b,&
Re: Combinatorics problem
by Fletch (Bishop) on Sep 03, 2009 at 22:06 UTC

    Not that you'll be able to turn in the perl list comprehensions one in for your homework either, but . . .

    $ echo 'main=do{putStrLn $ unlines $ map show [ (x,y,z) | x <- [1,2], +y <- "ab", z <- "#*&"]}' | runhaskell (1,'a','#') (1,'a','*') (1,'a','&') (1,'b','#') (1,'b','*') (1,'b','&') (2,'a','#') (2,'a','*') (2,'a','&') (2,'b','#') (2,'b','*') (2,'b','&')

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Thanks fletch. But could you please write your code a bit more clearly. I can't quite read it. Thanks
Re: Combinatorics problem
by JavaFan (Canon) on Sep 04, 2009 at 00:22 UTC
    say"@$_"for(*_=sub{!@_?():@_==1?map{[$_]}@{$_[0]}:map{my$x=$_;map{[$x, +@$_]}_(@_[1..$#_])}@{$_[0]}})->([1,2],["a","b"],["#","*","&"]); __END__ 1 a # 1 a * 1 a & 1 b # 1 b * 1 b & 2 a # 2 a * 2 a & 2 b # 2 b * 2 b &
      The code above contains a bug - it returns an empty list when no arguments are given, but it should return a reference to an empty list. Fixing the bug also means the code can be shortened:
      say"@$_"for(*_=sub{@_?map{my$x=$_;map{[$x,@$_]}_(@_[1..$#_])}@{$_[0]}: +[]})->([1,2],["a","b"],["#","*","&"]);
Re: Combinatorics problem
by aufflick (Deacon) on Sep 04, 2009 at 04:16 UTC
    I really hope this isn't homework...

    I keep thinking there must be a way to simplify this with matrix addition. Of course you need the matrices to be of the same order, but you could pad the matrices with empty strings. You'd also have to make the matrix addition code use the . operator instead of +.

    A good approach with this type of problem is to think of any information you know up front. As soon as we have the lists we can easily determine the total number of results (by multiplying the lengths together). From there we can work backwards.

    use strict; use warnings; my @lists = ( [1, 2], ['a', 'b'], ['#', '*', '&'], ); # we know the total number of results will be: my $num_results = 1; $num_results *= $_ for map {scalar @{$_}} @lists; my $max_i = $num_results - 1; # build the result list entries left to right my @res = map { '' } 0 .. $max_i; my $pivot = $num_results; for my $list (@lists) { my $j = -1; my $len = scalar @{$list}; $pivot = $pivot / $len; for my $i (0 .. $max_i) { $j++ if $i % $pivot == 0; $j = 0 if $j == $len; $res[$i] .= $list->[$j]; } } print join( "\n", @res), "\n";
    Making the result a list of lists instead of a list of strings is an exercise left to the reader ;)

Use SQL
by herveus (Prior) on Sep 04, 2009 at 10:56 UTC
    Howdy!

    Put the lists into separate tables. Generate the cross join of the whole set of tables. *poof*

    yours,
    Michael

      Using SQL, you can't be sure that the resulting list will preserve the order of the original lists.

      Unsorted original lists and the use of primary keys or clustered tables, the query optimizer, size of lists and blocking factor among others are things I can recall that might change the way the output is returned... :-(

        Howdy!

        Actually, you can ensure the order of the output, but it requires that the base tables include a column with a sort key. Then you have something you can use in an order by clause.

        Fundamentally, generating the cartesian product of the input lists will generate the elements of the output list. Controlling the sequence is a minor additional task.

        yours,
        Michael
Re: Combinatorics problem
by johngg (Canon) on Sep 04, 2009 at 21:00 UTC

    You could also use the glob built-in function although you may need to take care if your lists contain metacharacters significant to glob.

    $ perl -le 'print for glob( q{{a,b}{c,d}} );' ac ad bc bd $
    $ perl -le ' > @lists = ( > [ qw{ 1 2 3 } ], > [ qw{ a b } ], > [ qw{ X Y Z } ], > ); > $globStr = > join q{}, > map { qq{{@{ [ join q{,}, @$_ ] }}} } > @lists; > print for glob $globStr;' 1aX 1aY 1aZ 1bX 1bY 1bZ 2aX 2aY 2aZ 2bX 2bY 2bZ 3aX 3aY 3aZ 3bX 3bY 3bZ $

    I hope this is helpful.

    Cheers,

    JohnGG