diff options
author | Guillermo Ramos | 2019-06-18 10:07:29 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-06-18 10:08:43 +0200 |
commit | 966d8883d4c525c597bc58b8042529954d4998b7 (patch) | |
tree | f7657cf9b14029e09af88d2b3565a3975e01338a /013 | |
parent | 0d5b38b5b237d57c17065b5b3af08c7e7f5dc3ed (diff) | |
download | perlweekly-966d8883d4c525c597bc58b8042529954d4998b7.tar.gz |
[013#2]
Diffstat (limited to '013')
-rwxr-xr-x | 013/ch2.pl | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/013/ch2.pl b/013/ch2.pl new file mode 100755 index 0000000..89091ae --- /dev/null +++ b/013/ch2.pl @@ -0,0 +1,38 @@ +#!/usr/bin/env perl +# +# Write a script to demonstrate Mutually Recursive methods. Two methods are +# mutually recursive if the first method calls the second and the second calls +# first in turn. Using the mutually recursive methods, generate Hofstadter +# Female and Male sequences. +# (https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences) +################################################################################ + +use strict; +use warnings; + +use Memoize qw<memoize>; + +# Cache the results of previous computations +memoize('M'); +memoize('F'); + +sub M { + my $n = shift; + return $n == 0 + ? 0 + : $n - F(M($n-1)); +} + +sub F { + my $n = shift; + return $n == 0 + ? 1 + : $n - M(F($n-1)); +} + +die "Usage: $0 <iterations>\n" unless @ARGV == 1; + +print "M\tF\n-\t-\n"; +foreach my $n (0 .. shift) { + printf "%d\t%d\n", M($n), F($n); +} |