aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBob Lied <boblied+github@gmail.com>2024-01-15 10:29:26 -0600
committerBob Lied <boblied+github@gmail.com>2024-01-15 10:29:26 -0600
commitfaf09e55883803345ac3dd71b7055ff61479be3a (patch)
treef21ff8761fe17abf3b676126f30cb27c4fa4ba35
parent244a9670f9e964e12744ee0f93dfea0b6c3bd41c (diff)
downloadperlweeklychallenge-club-faf09e55883803345ac3dd71b7055ff61479be3a.tar.gz
perlweeklychallenge-club-faf09e55883803345ac3dd71b7055ff61479be3a.tar.bz2
perlweeklychallenge-club-faf09e55883803345ac3dd71b7055ff61479be3a.zip
Week 252, alternative solution for task 1
-rw-r--r--challenge-252/bob-lied/perl/ch-1.pl28
1 files changed, 28 insertions, 0 deletions
diff --git a/challenge-252/bob-lied/perl/ch-1.pl b/challenge-252/bob-lied/perl/ch-1.pl
index 35d16224fc..90da967a76 100644
--- a/challenge-252/bob-lied/perl/ch-1.pl
+++ b/challenge-252/bob-lied/perl/ch-1.pl
@@ -44,6 +44,26 @@ sub specialNumbers(@ints)
return sum0 map { $_ * $_ } @ints[ grep { $len % $_ == 0 } 1 .. $len ];
}
+sub factorsOf($n)
+{
+ use List::Util qw/uniqint/;
+ my @flist = (1, $n);
+ for my $f ( 2 .. int(sqrt($n)) )
+ {
+ push @flist, ($f, $n/$f) if $n % $f == 0;
+ }
+ return [ uniqint sort { $a <=> $b } @flist ]
+}
+
+sub sn2(@ints)
+{
+ use List::MoreUtils qw/before/;
+ my $len = @ints;
+ return 0 if $len == 0;
+ my @choose = map { $_ - 1 } before { $_ > $len } factorsOf($len)->@*;
+ return sum0 map { $_ * $_ } @ints[@choose];
+}
+
sub runTest
{
use Test2::V0;
@@ -53,5 +73,13 @@ sub runTest
is( specialNumbers(8 ), 64, "Singleton");
is( specialNumbers() , 0, "Empty list");
+ is( sn2(1,2,3,4), 21, "sn2 Example 1");
+ is( sn2(2,7,1,19,18,3), 63, "sn2 Example 2");
+ is( sn2(8 ), 64, "sn2 Singleton");
+ is( sn2() , 0, "sn2 Empty list");
+
+ is( factorsOf( 6), [1,2,3,6], "factorsOf 6");
+ is( factorsOf(36), [1,2,3,4,6,9,12,18,36], "factorsOf 36");
+
done_testing;
}