aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2022-07-09 23:09:27 +0100
committerGitHub <noreply@github.com>2022-07-09 23:09:27 +0100
commit3834c63efb086fa81a6f7a9158f6fd2f73b9a59f (patch)
tree462d1ac3426348cc249d166aedb669d849ac2f50
parent49012917fbbb441998c064ce1b4f8ee4f33bce1e (diff)
parent0c89351346bf747ed5dbecfd4fb10a3c1c998096 (diff)
downloadperlweeklychallenge-club-3834c63efb086fa81a6f7a9158f6fd2f73b9a59f.tar.gz
perlweeklychallenge-club-3834c63efb086fa81a6f7a9158f6fd2f73b9a59f.tar.bz2
perlweeklychallenge-club-3834c63efb086fa81a6f7a9158f6fd2f73b9a59f.zip
Merge pull request #6409 from choroba/ech172
Solve 172: Prime Partition & Five-number Summary by E. Choroba
-rwxr-xr-xchallenge-172/e-choroba/perl/ch-1.pl42
-rwxr-xr-xchallenge-172/e-choroba/perl/ch-2.pl21
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];