diff options
| author | Joelle Maslak <jmaslak@antelope.net> | 2019-06-17 11:06:54 -0700 |
|---|---|---|
| committer | Joelle Maslak <jmaslak@antelope.net> | 2019-06-17 11:06:54 -0700 |
| commit | af1ebf1ddb1ffed1f0f10aca8c31d79ba28f3421 (patch) | |
| tree | 67679fc12135d4b32389888e3acd019284df95ae | |
| parent | f7adb19d359ad829980bdfbbc5d2582fc0e6840f (diff) | |
| download | perlweeklychallenge-club-af1ebf1ddb1ffed1f0f10aca8c31d79ba28f3421.tar.gz perlweeklychallenge-club-af1ebf1ddb1ffed1f0f10aca8c31d79ba28f3421.tar.bz2 perlweeklychallenge-club-af1ebf1ddb1ffed1f0f10aca8c31d79ba28f3421.zip | |
Solution for 13.2 in P5 & P6
| -rwxr-xr-x | challenge-013/joelle-maslak/perl5/ch-2.pl | 37 | ||||
| -rwxr-xr-x | challenge-013/joelle-maslak/perl6/ch-2.p6 | 21 |
2 files changed, 58 insertions, 0 deletions
diff --git a/challenge-013/joelle-maslak/perl5/ch-2.pl b/challenge-013/joelle-maslak/perl5/ch-2.pl new file mode 100755 index 0000000000..92e9ba379d --- /dev/null +++ b/challenge-013/joelle-maslak/perl5/ch-2.pl @@ -0,0 +1,37 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +use v5.22; + +# Turn on method signatures +use feature 'signatures'; +no warnings 'experimental::signatures'; + +# If you try computing say 1000 of these, you get a mess without +# caching. It gives deep recursion warnings and slowness. So we use +# Memoize to speed this up. +use Memoize; + +memoize('F'); +sub F($n) { + return 1 if $n == 0; + return $n - M( F($n-1) ); +} + +memoize('M'); +sub M($n) { + return 0 if $n == 0; + return $n - F( M($n-1) ); +} + +die("Must provide number of elements") if @ARGV != 1; +my $len = +$ARGV[0]; + +my @f = map { F($_) } (0..($len-1)); +my @m = map { M($_) } (0..($len-1)); + +say "F: " . join(" ", @f); +say "M: " . join(" ", @m); + diff --git a/challenge-013/joelle-maslak/perl6/ch-2.p6 b/challenge-013/joelle-maslak/perl6/ch-2.p6 new file mode 100755 index 0000000000..da9c25c506 --- /dev/null +++ b/challenge-013/joelle-maslak/perl6/ch-2.p6 @@ -0,0 +1,21 @@ +#!/usr/bin/env perl6 +use v6; + +use experimental :cached; + +sub MAIN(UInt:D $length) { + my @f = lazy (0..∞).map: { F($_) }; + my @m = lazy (0..∞).map: { M($_) }; + + say "F: { @f[^$length] }"; + say "M: { @m[^$length] }"; +} + +multi sub F(0) { 1 } +multi sub M(0) { 0 } + +# We cache these results, but can't use the cached trait (because it's a +# multi?), so we do it the old-fashioned way. +multi sub F($n where * > 0 ) { state %c; %c{$n} //= $n - M( F($n-1) ) } +multi sub M($n where * > 0 ) { state %c; %c{$n} //= $n - F( M($n-1) ) } + |
