Advent Calendar 2024
| Day 10 | Day 11 |
The gift is presented by Simon Green
. Today he is talking about his solution to The Weekly Challenge - 261. This is re-produced for Advent Calendar 2024
from the original post.
Weekly Challenge 261
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 arra
My solution
Given that Perl
doesn’t care (most of the time) between numbers and strings, this is one of those challenges that is easier to do in Perl
.
my $element_sum = sum(@ints);
my $digit_sum = sum( map { split // } @ints );
say abs( $element_sum - $digit_sum );
The sum
function comes from List::Util
. The first line gets the sum of the elements. The second line splits the integers by the digits and calculates the sum. The final line calculates and display the absolute difference.
My Python
solution is as follows
def element_digit_sum(ints: list) -> int:
element_sum = sum(ints)
digit_sum = sum(int(i) for s in map(str, ints) for i in s)
return abs(element_sum - digit_sum)
It follows the same logic and the Perl
code. The second line does the following
- map(str, ints) turns the list of integers into a generator of strings
- for s in iterates over the generator
- for i in s iterates over each character in the string
- int(i) turns that character into an integer
- sum() turns the list of integers into a sum of the values
Examples
$ ./ch-1.py 1 2 3 45
36
$ ./ch-1.py 1 12 3
9
$ ./ch-1.py 1 2 3 4
0
$ ./ch-1.py 236 416 336 350
1296
Task #2: Dictionary Rank
You are given an array of integers, @ints and an integer $start..
Write a script to do the following:
1) Look for $start in the array @ints, if found multiply the number by 2
2) If not found stop the process otherwise repeat
In the end return the final value.
My solution
This seems relatively straight forward. I keep multiplying the start by two until the value does not appear in the list. For performance, I could have converted the list into a set (hash in Perl
), as checking in-ness (is that a word?) is faster that way. However, we are dealing with a small list, so it is not required.
def multiple_by_two(ints: list, start: int) -> int:
solution = start
while solution in ints:
solution *= 2
return solution
Examples
$ ./ch-2.py 5 3 6 1 12 3
24
$ ./ch-2.py 1 2 4 3 1
8
$ ./ch-2.py 5 6 7 2
2
If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.