diff options
| author | drbaggy <js5@sanger.ac.uk> | 2021-07-26 12:50:07 +0100 |
|---|---|---|
| committer | drbaggy <js5@sanger.ac.uk> | 2021-07-26 12:50:07 +0100 |
| commit | 3ebea6660bb9e212bb39008590758a023f7a71de (patch) | |
| tree | df7f6e7ad66b2891e298bd93b969fd41b02a58d3 | |
| parent | b9261a75ac76d2fc12a4d5ee179e2be3bb5a57c9 (diff) | |
| download | perlweeklychallenge-club-3ebea6660bb9e212bb39008590758a023f7a71de.tar.gz perlweeklychallenge-club-3ebea6660bb9e212bb39008590758a023f7a71de.tar.bz2 perlweeklychallenge-club-3ebea6660bb9e212bb39008590758a023f7a71de.zip | |
I think there is a bit of nasty code to add to "nth-ugly" to speed this up - which remembers where to start the inner for loops - but need to get my brain around it - at least this works - and is better than a full scan of 1..N as n gets larger
| -rw-r--r-- | challenge-123/james-smith/perl/ch-1.pl | 29 |
1 files changed, 22 insertions, 7 deletions
diff --git a/challenge-123/james-smith/perl/ch-1.pl b/challenge-123/james-smith/perl/ch-1.pl index 2348c8b946..6c24f48516 100644 --- a/challenge-123/james-smith/perl/ch-1.pl +++ b/challenge-123/james-smith/perl/ch-1.pl @@ -3,20 +3,35 @@ use strict; use warnings; -use feature qw(say); +use feature qw(say state); use Test::More; use Benchmark qw(cmpthese timethis); use Data::Dumper qw(Dumper); -my @TESTS = ( - [ 0, 1 ], -); +my @uglies = qw(1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 54 60 64 72 75 80 81 90 96 100 108 120 125 128 135 144 150 160 162 180 192 200 216 225 240 243 250 256 270 288 300 320 324 360 375 384 400 405 432 450 480 486 500 512 540 576 600 625 640 648 675 720 729 750 768 800 810 864 900 960 972 1000); -is( my_function($_->[0]), $_->[1] ) foreach @TESTS; +my $c=0; +my @TESTS = map { [ ++$c, $_ ] } @uglies; +is( nth_ugly($_->[0]), $_->[1] ) foreach @TESTS; done_testing(); -sub my_function { - return 1; +sub nth_ugly { + my $n = shift; + state @uglies; + @uglies=(1) unless @uglies; + while(1) { + return $uglies[$n-1] if $n <= @uglies; + ## Get the next ugly.... + my $next = 0; + foreach my $n (5,3,2) { + foreach(@uglies) { + next if $_ * $n <= $uglies[-1]; + $next = $_*$n if !$next || $next > $_*$n; + last; + } + } + push @uglies, $next; + } } |
