From c0af731be7392e728b19091e40d69a183cf2db60 Mon Sep 17 00:00:00 2001 From: Guillermo Ramos Date: Sun, 28 Apr 2019 13:36:15 +0200 Subject: 005#1 (functional) --- 005/ch1.pl | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 005/ch1.pl (limited to '005') diff --git a/005/ch1.pl b/005/ch1.pl new file mode 100644 index 0000000..1d020a6 --- /dev/null +++ b/005/ch1.pl @@ -0,0 +1,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"; + } +} -- cgit v1.2.3