The weekly challenge 238 - Task 1: Running Sum

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-238/#TASK1
 3 #
 4 # Task 1: Running Sum
 5 # ===================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to return the running sum of the given array. The running sum
10 # can be calculated as sum[i] = num[0] + num[1] + …. + num[i].
11 #
12 ## Example 1
13 ##
14 ## Input: @int = (1, 2, 3, 4, 5)
15 ## Output: (1, 3, 6, 10, 15)
16 #
17 ## Example 2
18 ##
19 ## Input: @int = (1, 1, 1, 1, 1)
20 ## Output: (1, 2, 3, 4, 5)
21 #
22 ## Example 3
23 ##
24 ## Input: @int = (0, -1, 1, 2)
25 ## Output: (0, -1, 0, 2)
26 #
27 ############################################################
28 ##
29 ## discussion
30 ##
31 ############################################################
32 #
33 # This one is straight forward: For each element, add it to
34 # the current sum and add the sum to the result array.
35 use strict;
36 use warnings;
37 
38 running_sum(1, 2, 3, 4, 5);
39 running_sum(1, 1, 1, 1, 1);
40 running_sum(0, -1, 1, 2);
41 
42 sub running_sum {
43    my @int = @_;
44    my $sum = 0;
45    my @result = ();
46    print "Input: (" . join(", ", @int) . ")\n";
47    foreach my $elem (@int) {
48       $sum += $elem;
49       push @result, $sum;
50    }
51    print "Output: (" . join(", ", @result) . ")\n";
52 }