Digits and doubling
Weekly challenge 261 — 18 March 2024
Week 261: 18 Mar 2024
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: 1 + 2 + 3 + 45 = 51 Digit Sum: 1 + 2 + 3 + 4 + 5 = 15 Absolute Difference: | 51 - 15 | = 36 Example 2 Input: @ints = (1,12,3) Output: 9 Element Sum: 1 + 12 + 3 = 16 Digit Sum: 1 + 1 + 2 + 3 = 7 Absolute Difference: | 16 - 7 | = 9 Example 3 Input: @ints = (1,2,3,4) Output: 0 Element Sum: 1 + 2 + 3 + 4 = 10 Digit Sum: 1 + 2 + 3 + 4 = 10 Absolute Difference: | 10 - 10 | = 0 Example 4 Input: @ints = (236, 416, 336, 350) Output: 1296
Each of the two required sums is an easy single line in Perl, and the difference a simple subtraction. The 'absolute' in the task description is superfluous, as no positive integer's digit sum can exceed itself.
The task description does not explicitly exclude negative integers, but the examples all use only positive integers, and we would need to be told, for example, whether to treat -45 as - 4 + 5 or - 4 - 5. I have assumed that we are only interested in positive values.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-03-18 use utf8; # Week 261 - task 1 - Element digit sum use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; my (@ints, $j); element_digit_sum(1, 2, 3, 45); element_digit_sum(1, 12, 3); element_digit_sum(1, 2, 3, 4); element_digit_sum(236, 416, 336, 350); # longer random example for $j (0 .. 49) { $ints[$j] = int(rand(1000)); } element_digit_sum(@ints); sub element_digit_sum { my (@ints, $digit_sum, $element_sum, $difference); # calculate sums @ints = @_; $element_sum += $_ for @ints; $digit_sum += $_ for split('', join('', @ints)); # calculate difference $difference = abs($element_sum - $digit_sum); say qq[\nInput: \@ints = (] . join(', ', @ints) . qq[)\n] . qq[Output: $difference (element sum = $element_sum, digit sum = $digit_sum)]; }
Input: @ints = (1, 2, 3, 45) Output: 36 (element sum = 51, digit sum = 15) Input: @ints = (1, 12, 3) Output: 9 (element sum = 16, digit sum = 7) Input: @ints = (1, 2, 3, 4) Output: 0 (element sum = 10, digit sum = 10) Input: @ints = (236, 416, 336, 350) Output: 1296 (element sum = 1338, digit sum = 42) Input: @ints = (498, 749, 269, 81, 991, 111, 388, 595, 450, 358, 632, 135, 343, 378, 512, 394, 855, 474, 197, 352, 962, 686, 930, 26, 799, 179, 141, 837, 779, 612, 714, 658, 40, 206, 330, 881, 67, 506, 113, 543, 281, 229, 252, 475, 165, 763, 61, 238, 30, 775) Output: 21375 (element sum = 22040, digit sum = 665)
Any content of this website which has been created by Peter Campbell Smith is in the public domain