perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 306 - Task 1: Odd Sum

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-306/#TASK1
 3 #
 4 # Task 1: Odd Sum
 5 # ===============
 6 #
 7 # You are given an array of positive integers, @ints.
 8 #
 9 # Write a script to return the sum of all possible odd-length subarrays of the
10 # given array. A subarray is a contiguous subsequence of the array.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (2, 5, 3, 6, 4)
15 ## Output: 77
16 ##
17 ## Odd length sub-arrays:
18 ## (2) => 2
19 ## (5) => 5
20 ## (3) => 3
21 ## (6) => 6
22 ## (4) => 4
23 ## (2, 5, 3) => 10
24 ## (5, 3, 6) => 14
25 ## (3, 6, 4) => 13
26 ## (2, 5, 3, 6, 4) => 20
27 ##
28 ## Sum => 2 + 5 + 3 + 6 + 4 + 10 + 14 + 13 + 20 => 77
29 #
30 ## Example 2
31 ##
32 ## Input: @ints = (1, 3)
33 ## Output: 4
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # We walk the array from the first element to the last and
42 # add the sum of all subarrays starting at the current element
43 # when the number of elements in that subarray is odd.
44 
45 use strict;
46 use warnings;
47 use List::Util qw(sum);
48 
49 odd_sum(2, 5, 3, 6, 4);
50 odd_sum(1, 3);
51 
52 sub odd_sum {
53    my @ints = @_;
54    print "Input: (" . join(",", @ints) . ")\n";
55    my $sum = 0;
56    foreach my $i (0..$#ints) {
57       foreach my $j ($i..$#ints) {
58          my @tmp = @ints[$i..$j];
59          if(scalar(@tmp) % 2) {
60             $sum += sum(@tmp);
61          }
62       }
63    }
64    print "Output: $sum\n";
65 }