Advent Calendar - December 2, 2024

Monday, Dec 2, 2024| Tags: Perl

Advent Calendar 2024

|   Day 1   |   Day 2   |


The gift is presented by Jorg Sommrey. Today he is talking about his solution to The Weekly Challenge - 252. This is re-produced for Advent Calendar 2024 from the original post.



Special Zeroes



Task 1: Special Numbers


You are given an array of integers, @ints.

Write a script to find the sum of the squares of all special elements of the given array.

An element $int[i] of @ints is called special if i divides n, i.e. n % i == 0.
Where n is the length of the given array.
Also the array is 1-indexed for the task.

Solution


We need to sum over the squared values of all elements having an 1-based index that divides the size of @ints. There is divisors in Math::Prime::Util that provides all divisors of a given number and there is PDL that can pick slices off, calculate the element-wise power of and the sum over an ndarray.

Putting these together in a single statement:


use PDL;
use PDL::NiceSlice;
use Math::Prime::Util 'divisors';

sub snss {
    sum pdl(@_)->(indx(divisors @_) - 1) ** 2
}

See the full solution


Task 2: Unique Sum Zero


You are given an integer, $n.

Write a script to find an array containing $n unique integers such that they add up to zero.

Solution


There are trivial solutions for even and odd values of $n:

- pairs of positive and negative integers with the same absolute value are distinct and sum to zero
- adding a zero to such a list keeps the sum at zero, but provides an odd number of elements

This results in:


use experimental 'signatures';

sub uniq_sum_zero ($n) {
    (-$n / 2 .. -1, (0) x ($n % 2), 1 .. $n / 2);
}

See the full solution



If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.

|   Advent Calendar 2024   |

SO WHAT DO YOU THINK ?

If you have any suggestions or ideas then please do share with us.

Contact with me