# Perl - permute? - Page 3

•  Subject
• Author
• Posted on

## Re: Perl - permute?

> John Bokma wrote:
>
> > At least I don't do it as an anonymous carrion bird.
>
> Yeah, anonymous, right, good Joke. You've realized you're in the Internet,
> right?

You do have a name, don't you?

## Re: Perl - permute?

Arndt Jonasson wrote:

> You do have a name, don't you?

Jep. I have.

--
http://www.dunkelheit.at /
sapere aude.

## Re: Perl - permute?

> 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

That isn't permutation.  3-deep nested loops should do it.

Xho

--
Usenet Newsgroup Service                        \$9.95/Month 30GB

## Re: Perl - permute?

>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.