The weekly challenge 334 - Task 1: Range Sum
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-334/#TASK1 3 # 4 # Task 1: Range Sum 5 # ================= 6 # 7 # You are given a list integers and pair of indices.. 8 # 9 # Write a script to return the sum of integers between the given indices (inclusive). 10 # 11 ## Example 1 12 ## 13 ## Input: @ints = (-2, 0, 3, -5, 2, -1), $x = 0, $y = 2 14 ## Output: 1 15 ## 16 ## Elements between indices (0, 2) => (-2, 0, 3) 17 ## Range Sum: (-2) + 0 + 3 => 1 18 # 19 # 20 ## Example 2 21 ## 22 ## Input: @ints = (1, -2, 3, -4, 5), $x = 1, $y = 3 23 ## Output: -3 24 ## 25 ## Elements between indices (1, 3) => (-2, 3, -4) 26 ## Range Sum: (-2) + 3 + (-4) => -3 27 # 28 # 29 ## Example 3 30 ## 31 ## Input: @ints = (1, 0, 2, -1, 3), $x = 3, $y = 4 32 ## Output: 2 33 ## 34 ## Elements between indices (3, 4) => (-1, 3) 35 ## Range Sum: (-1) + 3 => 2 36 # 37 # 38 ## Example 4 39 ## 40 ## Input: @ints = (-5, 4, -3, 2, -1, 0), $x = 0, $y = 3 41 ## Output: -2 42 ## 43 ## Elements between indices (0, 3) => (-5, 4, -3, 2) 44 ## Range Sum: (-5) + 4 + (-3) + 2 => -2 45 # 46 # 47 ## Example 5 48 ## 49 ## Input: @ints = (-1, 0, 2, -3, -2, 1), $x = 0, $y = 2 50 ## Output: 1 51 ## 52 ## Elements between indices (0, 2) => (-1, 0, 2) 53 ## Range Sum: (-1) + 0 + 2 => 1 54 # 55 ############################################################ 56 ## 57 ## discussion 58 ## 59 ############################################################ 60 # 61 # We just need to calculate the sum of a slice of the input array. 62 # We use sum() from List::Util which makes the whole operation really 63 # easy and quick. 64 65 use v5.36; 66 67 use List::Util qw( sum ); 68 69 range_sum( [-2, 0, 3, -5, 2, -1], 0, 2); 70 range_sum( [1, -2, 3, -4, 5], 1, 3); 71 range_sum( [1, 0, 2, -1, 3], 3, 4); 72 range_sum( [-5, 4, -3, 2, -1, 0], 0, 3); 73 range_sum( [-1, 0, 2, -3, -2, 1], 0, 2); 74 75 sub range_sum($ints, $x, $y) { 76 say "Input: (" . join(", ", @$ints) . "), $x, $y"; 77 say "Output: " . sum( @$ints[$x..$y] ); 78 }