diff options
| author | Markus "Holli" Holzer <holli.holzer@gmail.com> | 2020-04-04 10:48:02 +0200 |
|---|---|---|
| committer | Markus "Holli" Holzer <holli.holzer@gmail.com> | 2020-04-04 10:48:02 +0200 |
| commit | fcdd0884b74075c40e86cad2ab9a3ad02674e475 (patch) | |
| tree | 6651bee9db7b6dc3e3c5e41dc3daef62f90cbf09 /challenge-054/markus-holzer | |
| parent | 26e227ddc32dcd38a0b6430acea709471aaff899 (diff) | |
| download | perlweeklychallenge-club-fcdd0884b74075c40e86cad2ab9a3ad02674e475.tar.gz perlweeklychallenge-club-fcdd0884b74075c40e86cad2ab9a3ad02674e475.tar.bz2 perlweeklychallenge-club-fcdd0884b74075c40e86cad2ab9a3ad02674e475.zip | |
it doesnt get any faster =(
Diffstat (limited to 'challenge-054/markus-holzer')
| -rw-r--r-- | challenge-054/markus-holzer/raku/ch-2.p6 | 31 |
1 files changed, 20 insertions, 11 deletions
diff --git a/challenge-054/markus-holzer/raku/ch-2.p6 b/challenge-054/markus-holzer/raku/ch-2.p6 index bd4d4c2924..ec33d32087 100644 --- a/challenge-054/markus-holzer/raku/ch-2.p6 +++ b/challenge-054/markus-holzer/raku/ch-2.p6 @@ -1,34 +1,43 @@ -sub MAIN( Int $N ) +multi sub MAIN( Int $N, :$l ) { my $start = now; - my %result = 1 => 1; + my @result = Array.new( Any, 1, :shape( $N + 1 ) ); for 1..$N -> $n { my $current = 0; my $next = $n; - + my $cached; loop { # Dynamic programming: # see what you have computed so far, so you # don't have to compute it again - %result{ $n } = %result{ $next } and last - if %result{ $next }; + $cached = @result[ $next ]; + last if $cached; $next = $next %% 2 ?? $next / 2 !! $next * 3 + 1; $current++; } - %result{ $n } += $current; + @result[ $n ] = [ $n, $current + $cached ]; } - say "n: $_, length: %result{ $_ }" for - %result - .keys - .sort({ %result{ $^b } <=> %result{ $^a } }) - .head( 20 ); + say "n: { .[0] }, length: { .[1] }" for + @result + .skip + .sort( -*[1] ) + .head(20); say "runtime: { now - $start } seconds"; } +multi sub MAIN( Int $n, :$s ) +{ + say collatz( $n ).join( ',' ); +} + +sub collatz( Int $n ) +{ + $n, { $^n %% 2 ?? $^n / 2 !! $^n * 3 + 1 } ... { $^n == 1 } +} |
