aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorwanderdoc <wanderdoc@users.noreply.github.com>2025-08-17 18:58:35 +0200
committerGitHub <noreply@github.com>2025-08-17 18:58:35 +0200
commit1a1a7c433f9e3c58a90b52bdb46aca8c6b82a9b1 (patch)
tree1cd28141a463319f2cd490676468e388b376432c
parent36cc6a3f6b5b5d7f3e7c072a251435352c998dd2 (diff)
downloadperlweeklychallenge-club-1a1a7c433f9e3c58a90b52bdb46aca8c6b82a9b1.tar.gz
perlweeklychallenge-club-1a1a7c433f9e3c58a90b52bdb46aca8c6b82a9b1.tar.bz2
perlweeklychallenge-club-1a1a7c433f9e3c58a90b52bdb46aca8c6b82a9b1.zip
Create ch-1.pl
-rw-r--r--challenge-334/wanderdoc/perl/ch-1.pl76
1 files changed, 76 insertions, 0 deletions
diff --git a/challenge-334/wanderdoc/perl/ch-1.pl b/challenge-334/wanderdoc/perl/ch-1.pl
new file mode 100644
index 0000000000..c7ced5d4f8
--- /dev/null
+++ b/challenge-334/wanderdoc/perl/ch-1.pl
@@ -0,0 +1,76 @@
+#!perl
+use strict;
+use warnings FATAL => qw(all);
+
+=prompt
+You are given a list integers and pair of indices..
+Write a script to return the sum of integers between the given indices (inclusive).
+
+Example 1
+
+Input: @ints = (-2, 0, 3, -5, 2, -1), $x = 0, $y = 2
+Output: 1
+
+Elements between indices (0, 2) => (-2, 0, 3)
+Range Sum: (-2) + 0 + 3 => 1
+
+
+Example 2
+
+Input: @ints = (1, -2, 3, -4, 5), $x = 1, $y = 3
+Output: -3
+
+Elements between indices (1, 3) => (-2, 3, -4)
+Range Sum: (-2) + 3 + (-4) => -3
+
+
+Example 3
+
+Input: @ints = (1, 0, 2, -1, 3), $x = 3, $y = 4
+Output: 2
+
+Elements between indices (3, 4) => (-1, 3)
+Range Sum: (-1) + 3 => 2
+
+
+Example 4
+
+Input: @ints = (-5, 4, -3, 2, -1, 0), $x = 0, $y = 3
+Output: -2
+
+Elements between indices (0, 3) => (-5, 4, -3, 2)
+Range Sum: (-5) + 4 + (-3) + 2 => -2
+
+
+Example 5
+
+Input: @ints = (-1, 0, 2, -3, -2, 1), $x = 0, $y = 2
+Output: 1
+
+Elements between indices (0, 2) => (-1, 0, 2)
+Range Sum: (-1) + 0 + 2 => 1
+=cut
+
+
+use List::Util qw(sum);
+use Test2::V0 -no_srand => 1;
+
+
+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');
+done_testing();
+
+sub range_sum
+{
+ my ($aref, $x, $y) = @_;
+ die "Index beyond array limits!"
+ if ($x > $#$aref or $y > $#$aref or $x < 0 or $y < 0);
+ if ($x > $y)
+ {
+ ($x, $y) = ($y, $x);
+ }
+ return sum(@$aref[$x..$y]);
+}