blob: 1d020a61b726135a3813cebc0fbb132a7de87666 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#!/usr/bin/env perl
use strict;
use warnings;
# Functional implementation (tail-recursive)
sub anagrams {
sub iter {
my ($word, @acc) = @_;
if (length($word) == 0) {
return @acc;
} else {
my ($head, $tail) = $word =~ /^(.)(.*)$/;
@_ = $tail; # Next word will be the tail of the previous one
foreach my $anagram (@acc) {
for (my $i = 0; $i <= length($anagram); $i++) {
push(@_, $anagram);
substr($_[-1], $i, 0) = $head;
}
}
goto &iter;
}
}
iter($_[0], (""));
}
for (@ARGV) {
for (anagrams($_)) {
print $_, "\n";
}
}
|