diff options
| -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 } +} |
