in reply to Combinatorics problem
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.
Making the result a list of lists instead of a list of strings is an exercise left to the reader ;)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";
|
|---|