in reply to creating all possible random 'words' from 4 letters

Tangent Warning

For those trying to generate all possible 4-letter words [as in all 456,976 of them], glob is your friend:

#!/your/perl/here use warnings; use strict; use Data::Dumper; my $all_lowercase = '{' . join( ',', 'a'..'z') . '}'; my @x = glob "$all_lowercase" x 4; print "size of \@x = ", scalar @x, "\n"; print Dumper @x; __END__
Result:
size of @x = 456976 $VAR1 = 'aaaa'; $VAR2 = 'aaab'; $VAR3 = 'aaac'; $VAR4 = 'aaad'; $VAR5 = 'aaae'; [snip] $VAR456972 = 'zzzv'; $VAR456973 = 'zzzw'; $VAR456974 = 'zzzx'; $VAR456975 = 'zzzy'; $VAR456976 = 'zzzz';

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re: Re: creating all possible random 'words' from 4 letters
by blokhead (Monsignor) on Nov 07, 2003 at 18:56 UTC
    Using glob is pretty inventive. I like it, except that you generate a really big list*. As long as you're using all 26 letters, the increment operator will give you the list iteratively:
    my $str = 'aaaa'; print $str++, $/ while $str le 'dddd';
    No need to make an array with 26^4 elements!

    OK, using increment is fun, so let's be goofy and do it with just [a-d]:

    my $str = 'aaaa'; while ($str le 'dddd') { print $str++, $/; 1 while $str =~ s/(.)e/chr(1 + ord $1) . 'a'/e; }

    * Update: BrowserUK++ for setting me straight with glob. You learn something new every day here!

    blokhead

      If you don't want them all in one list, just call glob in a scalar context and it will act as an iterator for you.

      perl -le" print while glob '{A,B,C,D}'x4 "

      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      Hooray!
      Wanted!

        If you don't want them all in one list, just call glob in a scalar context and it will act as an iterator for you.

        ...but will still need to build the entire (easily huge) list into RAM, just not inside of Perl (and so will still fail except for near-trivial cases).

                        - tye
Re: Re: creating all possible random 'words' from 4 letters
by sauoq (Abbot) on Nov 07, 2003 at 22:07 UTC

    Or, more simply: my @x = 'aaaa' .. 'zzzz';

    :-)

    -sauoq
    "My two cents aren't worth a dime.";