perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 320 - Task 2: Sum Difference

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-320/#TASK2
 3 #
 4 # Task 2: Sum Difference
 5 # ======================
 6 #
 7 # You are given an array of positive integers.
 8 #
 9 # Write a script to return the absolute difference between digit sum and
10 # element sum of the given array.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1, 23, 4, 5)
15 ## Output: 18
16 ##
17 ## Element sum: 1 + 23 + 4 + 5 => 33
18 ## Digit sum: 1 + 2 + 3 + 4 + 5 => 15
19 ## Absolute difference: | 33 - 15 | => 18
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: @ints = (1, 2, 3, 4, 5)
25 ## Output: 0
26 ##
27 ## Element sum: 1 + 2 + 3 + 4 + 5 => 15
28 ## Digit sum: 1 + 2 + 3 + 4 + 5 => 15
29 ## Absolute difference: | 15 - 15 | => 0
30 #
31 #
32 ## Example 3
33 ##
34 ## Input: @ints = (1, 2, 34)
35 ## Output: 27
36 ##
37 ## Element sum: 1 + 2 + 34 => 37
38 ## Digit sum: 1 + 2 + 3 + 4 => 10
39 ## Absolute difference: | 37 - 10 | => 27
40 #
41 ############################################################
42 ##
43 ## discussion
44 ##
45 ############################################################
46 #
47 # Looking at each element in the list, we just add it to the element sum.
48 # Then we split the element into its digits and add all of those to the
49 # digit sum. In the end, we calculate the absolute difference of these two
50 # sums for the result.
51 
52 use v5.36;
53 
54 sum_difference(1, 23, 4, 5);
55 sum_difference(1, 2, 3, 4, 5);
56 sum_difference(1, 2, 34);
57 
58 sub sum_difference(@ints) {
59     say "Input: (" . join(", ", @ints) . ")";
60     my $elem_sum = 0;
61     my $digit_sum = 0;
62     foreach my $elem (@ints) {
63         $elem_sum += $elem;
64         my @digits = split //, $elem;
65         foreach my $digit (@digits) {
66             $digit_sum += $digit;
67         }
68     }
69     say "Output: " . abs($elem_sum - $digit_sum);
70 }