# all_sequences.pl (Was: Perl - permute?)

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

>Hi,
>How can I take an array (a,b,c,d,e) and list ALL possible [3 LETTER] combos
>of these letters, I want the output to look like

>abc
>acb
>aab
>aaa

Iterative or recursive, take your pick.

sub all_sequences {
my (\$alphabet, \$n) = @_;
return []   unless @\$alphabet;
return [''] unless \$n;

my @words = @\$alphabet;

for (2..\$n) {
for my \$i (reverse 0..\$#words) {
my \$word = \$words[\$i];
splice @words, \$i, 1, map "\$\$_", @\$alphabet;
}
}

return \@words;
}

sub all_sequences_recursive {
my (\$alphabet, \$n) = @_;
return []   unless @\$alphabet;
return [''] unless \$n;
return
[ map { my \$word = \$_; map "\$\$_", @\$alphabet }
@{all_sequences_recursive(\$alphabet, \$n-1)} ]
}

__END__

DB<1> x all_sequences_recursive([ qw(a b c d e) ], 3);
0  ARRAY(0x23dae4)
0  'aaa'
1  'aab'
2  'aac'

....

122  'eec'
123  'eed'
124  'eee'
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.

## Re: all_sequences.pl (Was: Perl - permute?)

kj wrote:
>
> >Hi,
> >How can I take an array (a,b,c,d,e) and list ALL possible [3 LETTER]
combos
> >of these letters, I want the output to look like
>
> >abc
> >acb
> >aab
> >aaa
>
> Iterative or recursive, take your pick.
>
> sub all_sequences {
>   my (\$alphabet, \$n) = @_;
>   return []   unless @\$alphabet;
>   return [''] unless \$n;
>
>   my @words = @\$alphabet;
>
>   for (2..\$n) {
>     for my \$i (reverse 0..\$#words) {
>       my \$word = \$words[\$i];
>       splice @words, \$i, 1, map "\$\$_", @\$alphabet;
>     }
>   }
>
>   return \@words;
> }
>
> sub all_sequences_recursive {
>   my (\$alphabet, \$n) = @_;
>   return []   unless @\$alphabet;
>   return [''] unless \$n;
>   return
>     [ map { my \$word = \$_; map "\$\$_", @\$alphabet }
>       @{all_sequences_recursive(\$alphabet, \$n-1)} ]
> }
>
> __END__
>
>   DB<1> x all_sequences_recursive([ qw(a b c d e) ], 3);
> 0  ARRAY(0x23dae4)
>    0  'aaa'
>    1  'aab'
>    2  'aac'
>
> ...
>
>    122  'eec'
>    123  'eed'
>    124  'eee'
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.

Here is a solution that will make you sick.
I cannot even say that it works because
my computer got stuck on it:

#!/usr/bin/perl

use warnings;
use strict;

my @a = ('a' .. 'e');
my \$max = 5*5*5;
my %results;
while (scalar keys %results < \$max)
{
my \$r1 = \$a[int rand(4)];
my \$r2 = \$a[int rand(4)];
my \$r3 = \$a[int rand(4)];
my \$result = "\$r1\$r2\$r3";
\$results++ if not \$results and print \$result,
"\n";
}
print "Here they are again, in order:\n";
print \$_, "\n" for sort keys %results;

I think it should work eventually :-)

wana