Created
May 13, 2019 22:35
-
-
Save thundergnat/3459bced681ea95394b522d5ad4e69ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Challenge #1 | |
#`[ Slow, naive, brute force perfect number calculation | |
sub is-perfect (Int $n) { | |
($n == sum grep $n %% *, 1 .. $n div 2) ?? | |
$n !! | |
Empty | |
} | |
] | |
# Faster perfect number calculation | |
sub is-perfect (Int $n) { | |
my $p = 2**$n - 1; | |
$n.is-prime && $p.is-prime ?? | |
$p * 2**($n - 1) !! | |
Empty | |
} | |
# Returns in a reasonable time for up to ~15 | |
.say for ( 1..* ).map( *.&is-perfect ).head(15); | |
# Challenge #2 | |
# Pass in an optional width parameter to center the phrases within that width | |
sub center (*@strings, :$width) { | |
my $pad = ceiling $width ?? | |
$width / 2 !! | |
2 R/ chars max @strings, :by(*.chars); | |
@strings.map( { ' ' x ($pad - .chars div 2) ~ $_ } ).join: "\n" | |
} | |
say center("This", "is", "a test of the", "center function"); | |
my ($, $columns) = qx/stty size/.words; | |
say center("This", "is", "a test of the", "center function", :width($columns)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment