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 ;)


In reply to Re: Combinatorics problem by aufflick
in thread Combinatorics problem by perlrocks

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.