From 3b56d588fdb085d2ff70a106ddd4b2a1c319177f Mon Sep 17 00:00:00 2001 From: Guillermo Ramos Date: Sun, 28 Apr 2019 20:05:38 +0200 Subject: [005#1] Comments --- 005/ch1.pl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) mode change 100644 => 100755 005/ch1.pl (limited to '005/ch1.pl') diff --git a/005/ch1.pl b/005/ch1.pl old mode 100644 new mode 100755 index 1d020a6..1c3436f --- 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) { -- cgit v1.2.3