aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-337/e-choroba/perl/ch-1.pl36
-rwxr-xr-xchallenge-337/e-choroba/perl/ch-2.pl23
2 files changed, 59 insertions, 0 deletions
diff --git a/challenge-337/e-choroba/perl/ch-1.pl b/challenge-337/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..5db9dfe323
--- /dev/null
+++ b/challenge-337/e-choroba/perl/ch-1.pl
@@ -0,0 +1,36 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+sub smaller_than_current(@num1) {
+ map { my $x = $_; scalar grep $_ < $x, @num1 } @num1
+}
+
+# Useful for large arrays with some values repeated.
+sub smaller_than_current_fast(@num1) {
+ my %cache;
+ map { my $x = $_; $cache{$_} //= scalar grep $_ < $x, @num1 } @num1
+}
+
+use Test2::V0;
+plan(2 * 5 + 1);
+
+for my $smaller_than_current (\&smaller_than_current,
+ \&smaller_than_current_fast
+) {
+ is [$smaller_than_current->(6, 5, 4, 8)], [2, 1, 0, 3], 'Example 1';
+ is [$smaller_than_current->(7, 7, 7, 7)], [0, 0, 0, 0], 'Example 2';
+ is [$smaller_than_current->(5, 4, 3, 2, 1)], [4, 3, 2, 1, 0], 'Example 3';
+ is [$smaller_than_current->(-1, 0, 3, -2, 1)], [1, 2, 4, 0, 3], 'Example 4';
+ is [$smaller_than_current->(0, 1, 1, 2, 0)], [0, 2, 2, 4, 0], 'Example 5';
+}
+
+my @long = map int rand 1000, 1 .. 1_000;
+is smaller_than_current(@long), smaller_than_current_fast(@long), 'same';
+
+use Benchmark qw{ cmpthese };
+cmpthese(-3, {
+ naive => sub { smaller_than_current(@long) },
+ optimized => sub { smaller_than_current_fast(@long) },
+});
diff --git a/challenge-337/e-choroba/perl/ch-2.pl b/challenge-337/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..268fb7db52
--- /dev/null
+++ b/challenge-337/e-choroba/perl/ch-2.pl
@@ -0,0 +1,23 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+use PDL;
+
+sub odd_matrix($row, $col, @locations) {
+ my $m = zeroes($col, $row);
+ for my $location (@locations) {
+ $m->slice($location->[1]) += 1;
+ $m->slice("", $location->[0]) += 1;
+ }
+ return ($m % 2)->sum
+}
+
+use Test::More tests => 5;
+
+is odd_matrix(2, 3, [0, 1], [1, 1]), 6, 'Example 1';
+is odd_matrix(2, 2, [1, 1], [0, 0]), 0, 'Example 2';
+is odd_matrix(3, 3, [0, 0], [1, 2], [2, 1]), 0, 'Example 3';
+is odd_matrix(1, 5, [0, 2], [0, 4]), 2, 'Example 4';
+is odd_matrix(4, 2, [1, 0], [3, 1], [2, 0], [0, 1]), 8, 'Example 5';