diff options
| author | E. Choroba <choroba@matfyz.cz> | 2021-11-29 18:01:15 +0100 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2021-11-29 18:02:59 +0100 |
| commit | c568b97a2e3dbf5da3aea5252444b8cf2082aeff (patch) | |
| tree | 8d2c2d9b8d8271185fde68df4712c920680693a6 | |
| parent | 87657d119305f8de1d4322f596a72ae619eacaac (diff) | |
| download | perlweeklychallenge-club-c568b97a2e3dbf5da3aea5252444b8cf2082aeff.tar.gz perlweeklychallenge-club-c568b97a2e3dbf5da3aea5252444b8cf2082aeff.tar.bz2 perlweeklychallenge-club-c568b97a2e3dbf5da3aea5252444b8cf2082aeff.zip | |
Add solutions to 141: Number Divisors & Like Numbers by E. Choroba
| -rwxr-xr-x | challenge-141/e-choroba/perl/ch-1.pl | 49 | ||||
| -rwxr-xr-x | challenge-141/e-choroba/perl/ch-2.pl | 23 |
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'; |
