Peter’s blog ✴ Week 238 ✴ 9 October 2023
THE WEEKLY CHALLENGE
Running persistence
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)
There's probably a one-liner for this, but I chose to do it in two. Note that by re-using the input @ints I didn't need to initialise the first member of the output array as it is the same as the input.
Simple yet elegant solution with cool interface to try it yourself. Thank you.
#!/usr/bin/perl use v5.16; # The Weekly Challenge - 2023-10-09 use utf8; # Week 237 task 1 - Running sum use strict; # Peter Campbell Smith use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge running_sum(1, 2, 3, 4, 5); running_sum(1, 1, 1, 1, 1); running_sum(0, -1, 1, 2); running_sum(34, 65, 12, -98, 87, 44, 72, 0, 39, 92); sub running_sum { my (@ints, $j, @sums); @ints = @_; say qq[\nInput: \@ints = (], join(', ', @ints) . ')'; for $j (1 .. @ints - 1) { $ints[$j] = $ints[$j - 1] + $ints[$j]; } say qq[Output: (] . join(', ', @ints) . ')'; }
7 lines of code
Input: @ints = (1, 2, 3, 4, 5) Output: (1, 3, 6, 10, 15) Input: @ints = (1, 1, 1, 1, 1) Output: (1, 2, 3, 4, 5) Input: @ints = (0, -1, 1, 2) Output: (0, -1, 0, 2) Input: @ints = (34, 65, 12, -98, 87, 44, 72, 0, 39, 92) Output: (34, 99, 111, 13, 100, 144, 216, 216, 255, 347)
Any content of this website which has been created by Peter Campbell Smith is in the public domain