The weekly challenge 261: Task 1: Element Digit Sum

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-261/#TASK1
 3 #
 4 # Task 1: Element Digit Sum
 5 # =========================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to evaluate the absolute difference between element and digit
10 # sum of the given array.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1,2,3,45)
15 ## Output: 36
16 ##
17 ## Element Sum: 1 + 2 + 3 + 45 = 51
18 ## Digit Sum: 1 + 2 + 3 + 4 + 5 = 15
19 ## Absolute Difference: | 51 - 15 | = 36
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (1,12,3)
24 ## Output: 9
25 ##
26 ## Element Sum: 1 + 12 + 3 = 16
27 ## Digit Sum: 1 + 1 + 2 + 3 = 7
28 ## Absolute Difference: | 16 - 7 | = 9
29 #
30 ## Example 3
31 ##
32 ## Input: @ints = (1,2,3,4)
33 ## Output: 0
34 ##
35 ## Element Sum: 1 + 2 + 3 + 4 = 10
36 ## Digit Sum: 1 + 2 + 3 + 4 = 10
37 ## Absolute Difference: | 10 - 10 | = 0
38 #
39 ## Example 4
40 ##
41 ## Input: @ints = (236, 416, 336, 350)
42 ## Output: 1296
43 #
44 ############################################################
45 ##
46 ## discussion
47 ##
48 ############################################################
49 #
50 # This is pretty straight forward, calculate the sum for each
51 # list, then calculate the digit sum by splitting each list
52 # element into its digits and then calculating the sum from there.
53 
54 use strict;
55 use warnings;
56 use List::Util qw(sum);
57 
58 element_digit_sum(1,2,3,45);
59 element_digit_sum(1,12,3);
60 element_digit_sum(1,2,3,4);
61 element_digit_sum(236, 416, 336, 350);
62 
63 sub element_digit_sum {
64    my @ints = @_;
65    print "Input: (" . join(", ", @ints) . ")\n";
66    my $elem_sum = sum(@ints);
67    my $digit_sum = 0;
68    foreach my $elem (@ints) {
69       $digit_sum += sum(split//, $elem);
70    }
71    print "Output: ", abs($elem_sum - $digit_sum), "\n";
72 }