diff options
author | Guillermo Ramos | 2019-04-28 20:05:38 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-04-28 20:05:38 +0200 |
commit | 3b56d588fdb085d2ff70a106ddd4b2a1c319177f (patch) | |
tree | db241f57dee803ad585281dae7804e8b53dd2cf2 /005/ch1.pl | |
parent | c0af731be7392e728b19091e40d69a183cf2db60 (diff) | |
download | perlweekly-3b56d588fdb085d2ff70a106ddd4b2a1c319177f.tar.gz |
[005#1] Comments
Diffstat (limited to '005/ch1.pl')
-rwxr-xr-x[-rw-r--r--] | 005/ch1.pl | 10 |
1 files changed, 8 insertions, 2 deletions
diff --git a/005/ch1.pl b/005/ch1.pl index 1d020a6..1c3436f 100644..100755 --- a/005/ch1.pl +++ b/005/ch1.pl @@ -3,15 +3,21 @@ use strict; use warnings; -# Functional implementation (tail-recursive) sub anagrams { + # Tail-recursive with accumulator; iterate over the word accumulating the + # anagrams that can be formed with the already-seen characters sub iter { + # @acc contains the already computed anagrams my ($word, @acc) = @_; if (length($word) == 0) { + # Finished consuming word -> return accumulator return @acc; } else { + # Split the current word: first letter vs the rest my ($head, $tail) = $word =~ /^(.)(.*)$/; @_ = $tail; # Next word will be the tail of the previous one + # Compute new anagrams by inserting the current letter in all the + # positions of the previous anagrams foreach my $anagram (@acc) { for (my $i = 0; $i <= length($anagram); $i++) { push(@_, $anagram); @@ -21,7 +27,7 @@ sub anagrams { goto &iter; } } - iter($_[0], ("")); + iter(shift, ("")); } for (@ARGV) { |