Perl Weekly Challenge 238: Running Sum

These are some answers to the Week 238, Task 1 of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on October 15, 2023 at 23:59). This blog post offers some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Task 1: Running Sum

You are given an array of integers.

Write a script to return the running sum of the given array. The running sum can be calculated as sum[i] = num[0] + num[1] + …. + num[i].

Example 1

Input: @int = (1, 2, 3, 4, 5)
Output: (1, 3, 6, 10, 15)

Example 2

Input: @int = (1, 1, 1, 1, 1)
Output: (1, 2, 3, 4, 5)

Example 3

Input: @int = (0, -1, 1, 2)
Output: (0, -1, 0, 2)

Running Sum in Raku

We use the [...] reduction meta-operator. When the wrapped operator is prefixed with a \, the reduction meta-operator returns a lazy list of all intermediate values. It is sometimes called a "triangular reduce". This leads to a very concise one-liner solution:

sub running-sum (@in) {
    return [\+] @in;
}

my @tests = <1 2 3 4 5>, <1 1 1 1 1>, <0 -1 1 2>;
for @tests -> @test {
    printf "%-15s => ", "@test[]";
    say join ", ", running-sum @test;
}

This program displays the following output:

$ raku ./running-sum.raku
1 2 3 4 5       => 1, 3, 6, 10, 15
1 1 1 1 1       => 1, 2, 3, 4, 5
0 -1 1 2        => 0, -1, 0, 2

Running Sum in Perl

Perl doesn't have a reduction meta-operator, so we use a simple loop to compute the items of the running sum.

use strict;
use warnings;
use feature 'say';

sub running_sum {
    my @sum = shift;
    for my $item (@_) {
        push @sum, $item + $sum[-1];
    }
    return @sum;
}

my @tests = ([<1 2 3 4 5>], [<1 1 1 1 1>], [<0 -1 1 2>]);
for my $test (@tests) {
    printf "%-15s => ", "@$test";
    say join ", ", running_sum @$test;
}

This program displays the following output:

$ perl ./running-sum.pl
1 2 3 4 5       => 1, 3, 6, 10, 15
1 1 1 1 1       => 1, 2, 3, 4, 5
0 -1 1 2        => 0, -1, 0, 2

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on October 22, 2023. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.