diff options
| author | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2019-04-28 19:35:25 +0100 |
|---|---|---|
| committer | Mohammad S Anwar <mohammad.anwar@yahoo.com> | 2019-04-28 19:35:25 +0100 |
| commit | bb011b4b85ef42b6f67f648732ed61be8fa374bd (patch) | |
| tree | 838037d2b0060c852022196c57a6ac1d4474eb64 /challenge-005 | |
| parent | 6eaab4c8fcac78775197a878a141adfdd678c7d5 (diff) | |
| download | perlweeklychallenge-club-bb011b4b85ef42b6f67f648732ed61be8fa374bd.tar.gz perlweeklychallenge-club-bb011b4b85ef42b6f67f648732ed61be8fa374bd.tar.bz2 perlweeklychallenge-club-bb011b4b85ef42b6f67f648732ed61be8fa374bd.zip | |
- Added solutions by Guillermo Ramos.
Diffstat (limited to 'challenge-005')
| -rw-r--r-- | challenge-005/guillermo-ramos/perl5/ch-1.pl | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/challenge-005/guillermo-ramos/perl5/ch-1.pl b/challenge-005/guillermo-ramos/perl5/ch-1.pl new file mode 100644 index 0000000000..1c3436f18a --- /dev/null +++ b/challenge-005/guillermo-ramos/perl5/ch-1.pl @@ -0,0 +1,37 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +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); + substr($_[-1], $i, 0) = $head; + } + } + goto &iter; + } + } + iter(shift, ("")); +} + +for (@ARGV) { + for (anagrams($_)) { + print $_, "\n"; + } +} |
