Task 1: Element Digit Sum
You are given an array of integers, @ints.
Write a script to evaluate the absolute difference between element and digit sum of the given array.
Example 1: Input: @ints = (1, 2, 3, 45) → Output: 36 (Element Sum: 51, Digit Sum: 15, |51 - 15| = 36)
Example 2: Input: @ints = (1, 12, 3) → Output: 9 (Element Sum: 16, Digit Sum: 7, |16 - 7| = 9)
Example 3: Input: @ints = (1, 2, 3, 4) → Output: 0
Example 4: Input: @ints = (236, 416, 336, 350) → Output: 1296
Method Explanation
For each integer in @ints, we compute two quantities:
- The element sum, which is the sum of all integers in the array.
- The digit sum, which is the sum of the base-10 digits across every element in the array.
Finally, we return the absolute difference |element_sum - digit_sum|. This requires a single linear pass over the elements and their decimal representations.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
signature_for element_digit_sum => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub element_digit_sum ($ints) {
my $element_sum = 0;
my $digit_sum = 0;
for my $int (@$ints) {
$element_sum += $int;
$digit_sum += $_ for split //, abs($int);
}
return abs( $element_sum - $digit_sum );
}
Python Solution
def element_digit_sum(ints: list[int]) -> int:
"""Return the absolute difference between the element sum and digit sum of ints."""
element_sum = sum(ints)
digit_sum = sum(int(c) for n in ints for c in str(abs(n)))
return abs(element_sum - digit_sum)