summaryrefslogtreecommitdiff
path: root/005
diff options
context:
space:
mode:
authorGuillermo Ramos2019-07-01 13:53:37 +0200
committerGuillermo Ramos2019-07-01 13:53:37 +0200
commitd916ca90c354b29cc1b0953508e9601576a4fd1e (patch)
treef1997d85fb0736cfb0abdf4cb534f81df8220df3 /005
parent85d335507fbb74df316bd5831e621e1a37884c35 (diff)
downloadperlweekly-d916ca90c354b29cc1b0953508e9601576a4fd1e.tar.gz
[all] Formatting, missing comments in header, etc
Diffstat (limited to '005')
-rwxr-xr-x005/ch1.pl58
1 files changed, 31 insertions, 27 deletions
diff --git a/005/ch1.pl b/005/ch1.pl
index 1c3436f..aa06105 100755
--- a/005/ch1.pl
+++ b/005/ch1.pl
@@ -1,37 +1,41 @@
#!/usr/bin/env perl
+#
+# Write a program which prints out all anagrams for a given word. For more information about Anagram, please check this wikipedia page
+# (https://en.wikipedia.org/wiki/Anagram)
+################################################################################
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, (""));
+ # 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";
- }
+ for (anagrams($_)) {
+ print $_, "\n";
+ }
}