aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2025-08-12 21:38:36 +0200
committerE. Choroba <choroba@matfyz.cz>2025-08-12 21:38:36 +0200
commitb5f2f9b920685056ecefdee54ef3b22c5a9db92a (patch)
tree29b57f9e95b0b19dc585e8f9113303eacbe0879f
parent3f0c25ac7a8089ff3d921c6e4926ff88ebd806cd (diff)
downloadperlweeklychallenge-club-b5f2f9b920685056ecefdee54ef3b22c5a9db92a.tar.gz
perlweeklychallenge-club-b5f2f9b920685056ecefdee54ef3b22c5a9db92a.tar.bz2
perlweeklychallenge-club-b5f2f9b920685056ecefdee54ef3b22c5a9db92a.zip
Add solutions to 334: Range Sum & Nearest Valid Point by E. Choroba
-rwxr-xr-xchallenge-334/e-choroba/perl/ch-1.pl22
-rwxr-xr-xchallenge-334/e-choroba/perl/ch-2.pl29
2 files changed, 51 insertions, 0 deletions
diff --git a/challenge-334/e-choroba/perl/ch-1.pl b/challenge-334/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..74a37df247
--- /dev/null
+++ b/challenge-334/e-choroba/perl/ch-1.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+use List::Util qw{ sum0 };
+
+sub range_sum($ints, $x, $y) {
+ no warnings 'uninitialized';
+ sum0(@$ints[$x .. $y])
+}
+
+use Test::More tests => 5 + 2;
+
+is range_sum([-2, 0, 3, -5, 2, -1], 0, 2), 1, 'Example 1';
+is range_sum([1, -2, 3, -4, 5], 1, 3), -3, 'Example 2';
+is range_sum([1, 0, 2, -1, 3], 3, 4), 2, 'Example 3';
+is range_sum([-5, 4, -3, 2, -1, 0], 0, 3), -2, 'Example 4';
+is range_sum([-1, 0, 2, -3, -2, 1], 0, 2), 1, 'Example 5';
+
+is range_sum([1, 2, 3], 1, 0), 0, 'Wrong order';
+is range_sum([1, 2, 3], 0, 10), 6, 'Out of bounds';
diff --git a/challenge-334/e-choroba/perl/ch-2.pl b/challenge-334/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..7743839721
--- /dev/null
+++ b/challenge-334/e-choroba/perl/ch-2.pl
@@ -0,0 +1,29 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental qw( signatures );
+
+sub nearest_valid_point($x, $y, @points) {
+ my $nearest;
+ for my $i (0 .. $#points) {
+ my $point = $points[$i];
+ next if $x != $point->[0] && $y != $point->[1];
+
+ my $distance = _distance($x, $y, @$point);
+ $nearest = $i if ! defined $nearest
+ || $distance < _distance($x, $y, @{ $points[$nearest] });
+ }
+ return $nearest // -1
+}
+
+sub _distance($x1, $y1, $x2, $y2) {
+ abs($x1 - $x2) + abs($y1 - $y2)
+}
+
+use Test::More tests => 5;
+
+is nearest_valid_point(3, 4, [1, 2], [3, 1], [2, 4], [2, 3]), 2, 'Example 1';
+is nearest_valid_point(2, 5, [3, 4], [2, 3], [1, 5], [2, 5]), 3, 'Example 2';
+is nearest_valid_point(1, 1, [2, 2], [3, 3], [4, 4]), -1, 'Example 3';
+is nearest_valid_point(0, 0, [0, 1], [1, 0], [0, 2], [2, 0]), 0, 'Example 4';
+is nearest_valid_point(5, 5, [5, 6], [6, 5], [5, 4], [4, 5]), 0, 'Example 5';