aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-03-06 18:38:16 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-03-10 15:39:43 +0100
commit50ca32a7d4399f4619a1ab5a2ed3b8d2a74fb88f (patch)
treed54d8006782a9d2d063d35feabcb47b2edd0f752
parentb77876aa95b2462fdf2af2113cda1257b7a13fad (diff)
downloadperlweeklychallenge-club-50ca32a7d4399f4619a1ab5a2ed3b8d2a74fb88f.tar.gz
perlweeklychallenge-club-50ca32a7d4399f4619a1ab5a2ed3b8d2a74fb88f.tar.bz2
perlweeklychallenge-club-50ca32a7d4399f4619a1ab5a2ed3b8d2a74fb88f.zip
Solution to task 2
-rwxr-xr-xchallenge-207/jo-37/perl/ch-2.pl63
1 files changed, 63 insertions, 0 deletions
diff --git a/challenge-207/jo-37/perl/ch-2.pl b/challenge-207/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..7f84bd9edf
--- /dev/null
+++ b/challenge-207/jo-37/perl/ch-2.pl
@@ -0,0 +1,63 @@
+#!/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 <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [N...]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+N...
+ calculate the H-Index for the given numbers
+
+EOS
+
+
+### Input and Output
+
+say hirsch(@ARGV);
+
+
+### Implementation
+
+sub hirsch {
+ # Compare the reverse-sorted list's elements with their index
+ # position and pick the largest index where the difference is
+ # positive. Finally adjust the zero-based array index to the
+ # one-based H-Index.
+ which(pdl(@_)->qsort->(-1:0) > sequence(scalar @_))->((-1)) + 1;
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ is hirsch(10, 8, 5, 4, 3), 4, 'example 1';
+ is hirsch(25, 8, 5, 3, 3), 3, 'example 2';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ is hirsch(9, 7, 6, 2, 1), 3, 'from Wikipedia';
+ is hirsch(1, 7, 6, 2, 9), 3, 'same, not sorted';
+ is hirsch(5, 5, 5, 5, 5), 5, 'last index';
+ }
+
+ done_testing;
+ exit;
+}