From daba8035ff9a31c70a87bc1f09fdb630ff48a387 Mon Sep 17 00:00:00 2001 From: Jörg Sommrey <28217714+jo-37@users.noreply.github.com> Date: Mon, 27 Feb 2023 15:55:15 +0100 Subject: Solution to task 2 --- challenge-206/jo-37/perl/ch-2.pl | 91 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100755 challenge-206/jo-37/perl/ch-2.pl diff --git a/challenge-206/jo-37/perl/ch-2.pl b/challenge-206/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..79c301738a --- /dev/null +++ b/challenge-206/jo-37/perl/ch-2.pl @@ -0,0 +1,91 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0 '!float'; +use PDL; +use PDL::NiceSlice; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die < c, i.e. the two pairs "overlap". +# We build a different pairing where b and c are +# exchanged and all other pairs remain unaltered, i.e. +# P' = (a, c) and Q' = (b, d) +# The new contributions to the target function are +# min(P') = a = min(P) (from the precondition a < c) and +# min(Q') = min(b, d) > min(c, d) = min(Q) (from our assumption b > c +# and the precondition c < d) +# All summands in the target function remain unchanged with the +# exception of Q', which increased from Q. +# +# There is only one partitioning into pairs where none of the pairs +# overlap: Taking the pairs as adjacent elements from the sorted list. +# From the above considerations, this partitioning maximizes the target +# function. +# +# A long introduction to a short solution: +sub max_pairsum { + # Sum over the first elements of successive pairs taken from the + # sorted list. + sum pdl(@_)->qsort->(0:-2:2); +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is max_pairsum(1,2,3,4), 4, 'example 1'; + is max_pairsum(0,2,1,3), 2, 'example 2'; + } + + SKIP: { + skip "tests" unless $tests; + } + + done_testing; + exit; +} -- cgit