aboutsummaryrefslogtreecommitdiff
path: root/challenge-149
diff options
context:
space:
mode:
authordrbaggy <js5@sanger.ac.uk>2022-07-04 21:10:19 +0100
committerdrbaggy <js5@sanger.ac.uk>2022-07-04 21:10:19 +0100
commit251b2bd8b0ff8d3b1262173c33a4e999cf37846a (patch)
treee6d58a6a75f6a895cb07762b0183860f48096b9d /challenge-149
parent9a0e9aa937cd71b048889a57f68896e5187466ac (diff)
downloadperlweeklychallenge-club-251b2bd8b0ff8d3b1262173c33a4e999cf37846a.tar.gz
perlweeklychallenge-club-251b2bd8b0ff8d3b1262173c33a4e999cf37846a.tar.bz2
perlweeklychallenge-club-251b2bd8b0ff8d3b1262173c33a4e999cf37846a.zip
new stuff
Diffstat (limited to 'challenge-149')
-rw-r--r--challenge-149/james-smith/perl/ch-1.pl50
1 files changed, 42 insertions, 8 deletions
diff --git a/challenge-149/james-smith/perl/ch-1.pl b/challenge-149/james-smith/perl/ch-1.pl
index 52c15c2a2d..c86d4bc5a6 100644
--- a/challenge-149/james-smith/perl/ch-1.pl
+++ b/challenge-149/james-smith/perl/ch-1.pl
@@ -8,17 +8,51 @@ use Test::More;
use Benchmark qw(cmpthese timethis);
use Data::Dumper qw(Dumper);
+my $N = @ARGV?$ARGV[0]:20;
+
+if( $N > 0 ) {
+ compact($N);
+} else {
+ expanded(-$N);
+}
+
# As an array we don't need to keep the fibonacci numbers
# We need them as the keys to the hash %fib which we use
# to check that a digit sum is a fibonacci number. Instead
# We only keep the last two values $fa & $fb
-for( my($n,$ds,$i,$fa,$fb,%fib)=(@ARGV?$ARGV[0]:20,0,0,1,1,0,1,1,1);
- $n; $i++,$ds=0 ) {
- $ds+=$_ foreach split //,$i;
- ## If we dont have a large enough fib add the next one...
- ## Digit sum can only be 1 larger than current maximum
- ## fibonacci.
- ($fib{$fa+$fb},$fa,$fb)=(1,$fb,$fa+$fb) if $ds > $fb;
- $n--,say $i if exists $fib{$ds};
+
+## If we dont have a large enough fib for the digit sum
+## add the next one...
+## Digit sum can only be 1 larger than current maximum
+## fibonacci so only need to add 1...
+
+sub compact {
+ for( my($n,$ds,$i,$fa,$fb,%fib)=($_[0],0,0,1,1,0,1,1,1);
+ $n; $i++,$ds=0 ) {
+ $ds+=$_ for split //,$i;
+ ($fib{$fa+$fb},$fa,$fb)=(1,$fb,$fa+$fb) if $ds > $fb;
+ $n--,say $i if exists $fib{$ds};
+ }
+}
+
+sub expanded {
+ my $n = $_[0];
+ my ( $fa, $fb ) = (1,1);
+ my %fib = ( 0 => 1, 1 => 1 );
+ my $i = 0;
+
+ while($n) {
+ my $ds = 0;
+ $ds += $_ for split //, $i;
+ if($ds > $fb) {
+ ( $fa, $fb ) = ( $fb, $fa + $fb );
+ $fib{ $fb } = 1;
+ }
+ if( exists $fib{$ds} ) {
+ $n--;
+ say $i;
+ }
+ $i++;
+ }
}