aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-12-01 18:20:22 +0000
committerGitHub <noreply@github.com>2021-12-01 18:20:22 +0000
commit2f71cf14f537ec7cfc9916f39a5b0866b276a321 (patch)
treeda080ceb64f0d6db8ee4bf19a01fb91c36fc1c1f
parent478a98aac3dd28d39ae834136286ae936666bed5 (diff)
parentc568b97a2e3dbf5da3aea5252444b8cf2082aeff (diff)
downloadperlweeklychallenge-club-2f71cf14f537ec7cfc9916f39a5b0866b276a321.tar.gz
perlweeklychallenge-club-2f71cf14f537ec7cfc9916f39a5b0866b276a321.tar.bz2
perlweeklychallenge-club-2f71cf14f537ec7cfc9916f39a5b0866b276a321.zip
Merge pull request #5309 from choroba/ech141
Add solutions to 141: Number Divisors & Like Numbers by E. Choroba
-rwxr-xr-xchallenge-141/e-choroba/perl/ch-1.pl49
-rwxr-xr-xchallenge-141/e-choroba/perl/ch-2.pl23
2 files changed, 72 insertions, 0 deletions
diff --git a/challenge-141/e-choroba/perl/ch-1.pl b/challenge-141/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..ef9aabe4bd
--- /dev/null
+++ b/challenge-141/e-choroba/perl/ch-1.pl
@@ -0,0 +1,49 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use feature qw{ say };
+
+use constant {
+ DIVISOR_TALLY => 8,
+ RESULT_TALLY => 10,
+};
+
+sub number_divisors_full {
+ my @results;
+ my $i = 1;
+ while (@results < RESULT_TALLY) {
+ my @d = grep 0 == $i % $_, 1 .. $i;
+ push @results, $i if @d == DIVISOR_TALLY;
+ } continue {
+ ++$i;
+ }
+ return @results
+}
+
+sub number_divisors_short {
+ my @results;
+ my $i = 1;
+ while (@results < RESULT_TALLY) {
+ my $divisor_tally = 0;
+ my $s = sqrt $i;
+ for my $d (1 .. $s) {
+ $divisor_tally += ($d == $s) ? 1 : 2 if 0 == $i % $d;
+ }
+ push @results, $i if $divisor_tally == DIVISOR_TALLY;
+ } continue {
+ ++$i;
+ }
+ return @results
+}
+
+say join ', ', number_divisors_short();
+
+use Test2::V0;
+plan 1;
+is [number_divisors_short], [number_divisors_full], 'same';
+
+use Benchmark qw{ cmpthese };
+cmpthese(-3, {
+ full => \&number_divisors_full,
+ short => \&number_divisors_short,
+});
diff --git a/challenge-141/e-choroba/perl/ch-2.pl b/challenge-141/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..82eeaabaee
--- /dev/null
+++ b/challenge-141/e-choroba/perl/ch-2.pl
@@ -0,0 +1,23 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw{ signatures bitwise };
+
+my @MASK = ("\x00", "\xFF");
+sub like_numbers ($digits, $divisor) {
+ my $length = length $digits;
+ my $count = 0;
+ for my $indicator (1 .. 2 ** $length - 2) {
+ my $mask = sprintf('%0*b', $length, $indicator)
+ =~ s/(.)/$MASK[$1]/gr;
+ my $candidate = ($mask &. $digits) =~ tr/\x00//dr;
+ ++$count if 0 == $candidate % $divisor;
+ }
+ return $count
+}
+
+use Test2::V0;
+plan 2;
+
+is like_numbers(1234, 2), 9, 'Example 1';
+is like_numbers(768, 4), 3, 'Example 2';