diff options
| author | E. Choroba <choroba@matfyz.cz> | 2022-07-09 20:53:17 +0200 |
|---|---|---|
| committer | E. Choroba <choroba@matfyz.cz> | 2022-07-09 20:53:17 +0200 |
| commit | 0c89351346bf747ed5dbecfd4fb10a3c1c998096 (patch) | |
| tree | 6ddc9d03e595dab898729a04e665b12cc52dce89 | |
| parent | 691f04963d707495eae490ff7758740af5aa6d70 (diff) | |
| download | perlweeklychallenge-club-0c89351346bf747ed5dbecfd4fb10a3c1c998096.tar.gz perlweeklychallenge-club-0c89351346bf747ed5dbecfd4fb10a3c1c998096.tar.bz2 perlweeklychallenge-club-0c89351346bf747ed5dbecfd4fb10a3c1c998096.zip | |
Solve 172: Prime Partition & Five-number Summary by E. Choroba
| -rwxr-xr-x | challenge-172/e-choroba/perl/ch-1.pl | 42 | ||||
| -rwxr-xr-x | challenge-172/e-choroba/perl/ch-2.pl | 21 |
2 files changed, 63 insertions, 0 deletions
diff --git a/challenge-172/e-choroba/perl/ch-1.pl b/challenge-172/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..1f02f50990 --- /dev/null +++ b/challenge-172/e-choroba/perl/ch-1.pl @@ -0,0 +1,42 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental 'signatures'; + +use Math::Prime::Util qw{ is_prime }; + +# Run faster. +use Memoize; +memoize '_prime_partition'; + +sub prime_partition ($sum, $size) { + _prime_partition($sum, $size, 2) +} + +sub _prime_partition ($sum, $size, $min) { + if ($size == 2) { + for my $p ($min .. $sum / 2) { + next unless is_prime($p); + + return [$p, $sum - $p] if is_prime($sum - $p) && $sum != $p * 2; + } + } else { + for my $p ($min .. $sum / $size) { + next unless is_prime($p); + + my $rest = _prime_partition($sum - $p, $size - 1, $p + 1); + return [$p, @$rest] if @$rest; + } + } + return [] +} + +use Test::More tests => 5; + +is_deeply prime_partition(18, 2), [5, 13], 'Example 1'; +is_deeply prime_partition(19, 3), [3, 5, 11], 'Example 2'; + +is_deeply prime_partition(9, 3), [], 'No solution'; +is_deeply prime_partition(4, 2), [], 'No duplicates'; +is_deeply prime_partition(400, 12), + [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 43, 199], 'Long list'; diff --git a/challenge-172/e-choroba/perl/ch-2.pl b/challenge-172/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..c438f88c50 --- /dev/null +++ b/challenge-172/e-choroba/perl/ch-2.pl @@ -0,0 +1,21 @@ +#! /usr/bin/perl +use warnings; +use strict; + +use PDL; + +sub five_number_summary { + my ($data) = @_; + return map pdl(@$data)->pctover($_), 0, 1/4, 0.5, 0.75, 1 +} + +use Test::More tests => 2; + +# This test fails. PDL doesn't use a simple interpolation. +is_deeply [five_number_summary([0, 0, 1, 2, 63, 61, 27, 13])], + [0, 0.5, 7.5, 44, 63]; + +# This is the actual result. It corresponds to R's summary() rather +# than fivenum(). +is_deeply [five_number_summary([0, 0, 1, 2, 63, 61, 27, 13])], + [0, 0.75, 7.5, 35.5, 63]; |
