From ebb2f495aea2f7902ebac5df76a9f778c46169a5 Mon Sep 17 00:00:00 2001 From: Jörg Sommrey <28217714+jo-37@users.noreply.github.com> Date: Mon, 14 Nov 2022 20:31:06 +0100 Subject: Solution to task 1 --- challenge-191/jo-37/perl/ch-1.pl | 75 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100755 challenge-191/jo-37/perl/ch-1.pl (limited to 'challenge-191') diff --git a/challenge-191/jo-37/perl/ch-1.pl b/challenge-191/jo-37/perl/ch-1.pl new file mode 100755 index 0000000000..5b446c688e --- /dev/null +++ b/challenge-191/jo-37/perl/ch-1.pl @@ -0,0 +1,75 @@ +#!/usr/bin/perl -s + +use v5.16; +use Test2::V0 '!float'; +use PDL; + +our ($tests, $examples); + +run_tests() if $tests || $examples; # does not return + +die <dummy(0); + + my $n = long(@_); + # Find the indices of the two largest items. + maximum_n_ind($n, my $max2 = zeroes(indx, 2)); + + # Check if the maximum item is at least twice the next. As items + # are integers, we may compare the scalar product of the maximum two + # items with the weight vector against -0.5 to gain the requested + # -1/1 result. + ($n->index($max2) x $w)->sclr <=> -0.5; +} + + +### Examples and tests + +sub run_tests { + SKIP: { + skip "examples" unless $examples; + + is twice_largest(1, 2, 3, 4), -1, 'Example 1'; + is twice_largest(1, 2, 0, 5), 1, 'Example 2'; + is twice_largest(2, 6, 3, 1), 1, 'Example 3'; + is twice_largest(4, 5, 2, 3), -1, 'Example 4'; + } + + SKIP: { + skip "tests" unless $tests; + + is twice_largest(1, 3, 3), -1, 'non-unique max'; + is twice_largest(-10, 1, -20), 1, 'negative items'; + } + + done_testing; + exit; +} -- cgit