From 0c89351346bf747ed5dbecfd4fb10a3c1c998096 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Sat, 9 Jul 2022 20:53:17 +0200 Subject: Solve 172: Prime Partition & Five-number Summary by E. Choroba --- challenge-172/e-choroba/perl/ch-1.pl | 42 ++++++++++++++++++++++++++++++++++++ challenge-172/e-choroba/perl/ch-2.pl | 21 ++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100755 challenge-172/e-choroba/perl/ch-1.pl create mode 100755 challenge-172/e-choroba/perl/ch-2.pl 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]; -- cgit