Re: generating a wordlist from an array of arrays



Adriano Ferreira wrote:
> On 9/29/05, mark berger <mb@xxxxxxxxxxx> wrote:
>>hey list. i stuck with gererating a wordlist from a changing
>>multidimensional array. each entry in the array contains a list with the
>>possible values.
>
> I am bit rusty, because it took me a little too long to make it work,
> but here is a recursive solution:
>
> #!/usr/bin/perl
>
> use strict;
> use warnings;
>
> # stuff( 'ab', qw(x y z) ) => qw(abx aby abz)
> sub stuff {
> my $first = shift @_;
> return map { "$first$_" } @_;
> }
>
> # gen_list( [qw(a b)], [qw(x y)] ) => qw(ax ay bx by)
> sub gen_list {
> return () unless @_;
>
> my $suffixes = pop @_;
> return @$suffixes unless @_;
>
> return map { stuff($_, @$suffixes) } gen_list(@_);
> }
>
> my @wordlayout = ([qw(a b)], [qw(c)], [qw(d e f)]);
> my @list = gen_list(@wordlayout);
> print "list: @list\n";
>
> What surprised me was the hassle of my first solution which had too
> many 'my' variables. But when I saw it working, a prune of the code,
> preserving readability, made it shorter than I would have expected.

If you want it shorter you don't need the 'stuff' sub:

sub gen_list {
return unless @_;

my $suffixes = pop;
return @$suffixes unless @_;

map { my $first = $_; map "$first$_", @$suffixes } gen_list( @_ );
}




John
--
use Perl;
program
fulfillment
.



Relevant Pages

  • Re: generating a wordlist from an array of arrays
    ... > multidimensional array. ... I am bit rusty, because it took me a little too long to make it work, ... but here is a recursive solution: ... sub gen_list { ...
    (perl.beginners)
  • How to pass a Function returning an array as a parameter
    ... If a have a function which returns a multidimensional array. ... Function CreateAnArray() ... Sub UseOneArrayas String) ...
    (microsoft.public.word.vba.beginners)
  • Are arrCart here is a Table?
    ... this source code form a shopping-cart, I'm confuseing on the array of ... "arrCart", is it a table? ... a multidimensional array seems like a table ... Sub CartAddItem ...
    (microsoft.public.inetserver.asp.general)