Camel
Peter
Peter Campbell Smith

A slice of New York

Weekly challenge 334 — 11 August 2025

Week 334: 11 Aug 2025

Task 1

Task — Range sum

You are given a list integers and pair of indices. Write a script to return the sum of the integers between the given indices (inclusive).

Examples


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

Analysis

Perl's implementation of array slices reduces this task to:

$sum += $_ for @integers[$x .. $y];

In 'real life' one would check that $x and $y were within the bounds of the array and that $y >= $x, but as Perl gives an intelligible error message if those conditions occur I think I'll leave it at that.

Try it 

Try running the script with any input:



example: 1, 2, 3, 4, 5



example: 1, 3

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-08-11
use utf8;     # Week 334 - task 1 - Range sum
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

range_sum([-2, 0, 3, -5, 2, -1], 0, 2);
range_sum([1, -2, 3, -4, 5], 1, 3);
range_sum([1, 0, 2, -1, 3], 3, 4);
range_sum([-5, 4, -3, 2, -1, 0], 0, 3);
range_sum([-1, 0, 2, -3, -2, 1], 0, 2);

sub range_sum {
    
    my (@integers, $from, $to, $sum);
    
    # do it
    @integers = @{$_[0]};
    $sum += $_ for @integers[$_[1] .. $_[2]];
    
    say qq[\nInput:  \@integers = (] . join(', ', @integers) . qq[), \$x = $_[1], \$y = $_[2]]; 
    say qq[Output: $sum];
}


Output


Input:  @integers = (-2, 0, 3, -5, 2, -1), $x = 0, $y = 2
Output: 1

Input:  @integers = (1, -2, 3, -4, 5), $x = 1, $y = 3
Output: -3

Input:  @integers = (1, 0, 2, -1, 3), $x = 3, $y = 4
Output: 2

Input:  @integers = (-5, 4, -3, 2, -1, 0), $x = 0, $y = 3
Output: -2

Input:  @integers = (-1, 0, 2, -3, -2, 1), $x = 0, $y = 2
Output: 1

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain