The weekly challenge 225 - Task 2: Left Right Sum Diff
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-225/#TASK2 3 # 4 # Task 2: Left Right Sum Diff 5 # Submitted by: Mohammad S Anwar 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to return left right sum diff array as shown below: 10 # 11 # @ints = (a, b, c, d, e) 12 # 13 # @left = (0, a, (a+b), (a+b+c)) 14 # @right = ((c+d+e), (d+e), e, 0) 15 # @left_right_sum_diff = ( | 0 - (c+d+e) |, 16 # | a - (d+e) |, 17 # | (a+b) - e |, 18 # | (a+b+c) - 0 | ) 19 # 20 ## 21 ## WARNING: this explaination isn't entirely correct. As per 22 ## https://leetcode.com/problems/left-and-right-sum-differences/ 23 ## it would make more sense to have an additional element 24 ## (a+b+c+d) at the end of @left and ((b+c+d+e) at the beginning 25 ## of @right, which also the examples demonstrate: 26 ## 27 # 28 ## Example 1: 29 ## 30 ## Input: @ints = (10, 4, 8, 3) 31 ## Output: (15, 1, 11, 22) 32 ## 33 ## @left = (0, 10, 14, 22) 34 ## @right = (15, 11, 3, 0) 35 ## 36 ## @left_right_sum_diff = ( |0-15|, |10-11|, |14-3|, |22-0|) 37 ## = (15, 1, 11, 22) 38 # 39 ## Example 2: 40 ## 41 ## Input: @ints = (1) 42 ## Output: (0) 43 ## 44 ## @left = (0) 45 ## @right = (0) 46 ## 47 ## @left_right_sum_diff = ( |0-0| ) = (0) 48 # 49 ## Example 3: 50 ## 51 ## Input: @ints = (1, 2, 3, 4, 5) 52 ## Output: (14, 11, 6, 1, 19) 53 ## 54 ## @left = (0, 1, 3, 6, 10) 55 ## @right = (14, 12, 9, 5, 0) 56 ## 57 ## @left_right_sum_diff = ( |0-14|, |1-12|, |3-9|, |6-5|, |10-0|) 58 ## = (14, 11, 6, 1, 10) 59 # 60 ############################################################ 61 ## 62 ## discussion 63 ## 64 ############################################################ 65 # 66 # First, calculate @left and @right, then calculate the 67 # @left_right_sum_diff 68 69 use strict; 70 use warnings; 71 72 left_right_sum_diff(10, 4, 8, 3); 73 left_right_sum_diff(1); 74 left_right_sum_diff(1, 2, 3, 4, 5); 75 76 sub left_right_sum_diff { 77 my @ints = @_; 78 print "Input: (" . join(", ", @ints) . ")\n"; 79 my ($current_left, $current_right) = (0, 0); 80 my @left = (); 81 my @right = (); 82 foreach my $index (0..$#ints) { 83 push @left, $current_left; 84 $current_left += $ints[$index]; 85 unshift @right, $current_right; 86 $current_right += $ints[ $#ints - $index ]; 87 } 88 my @left_right_sum_diff = (); 89 foreach my $index (0..$#ints) { 90 $left_right_sum_diff[$index] = abs($left[$index] - $right[$index]); 91 } 92 print "Output: (" . join(", ", @left_right_sum_diff) . ")\n"; 93 }