Robbie Hatley's Solutions To The Weekly Challenge #252
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:
This week (2024-01-14 through 2024-01-20) is weekly challenge #252. Its tasks are as follows:
Task 252-1: Special Numbers Submitted by: Mohammad S Anwar 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. Example 1: Input: @ints = (1, 2, 3, 4) Output: 21 There are exactly 3 special elements in the given array: $ints[1] since 1 divides 4 $ints[2] since 2 divides 4 $ints[4] since 4 divides 4 Hence, the sum of the squares of all special elements of the given array is: 1 * 1 + 2 * 2 + 4 * 4 = 21. Example 2: Input: @ints = (2, 7, 1, 19, 18, 3) Output: 63 There are exactly 4 special elements in the given array: $ints[1] since 1 divides 6, $ints[2] since 2 divides 6, $ints[3] since 3 divides 6, and $ints[6] since 6 divides 6. Hence, the sum of the squares of all special elements of the given array is: 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63
I'll handle this by making a sub with an accumulator $accum set to 0, then for each element of the array, if it's "special", add its square to $accum. To handle the "1 indexing", I'll let $i vary from 1 to $n, but use [$i-1] for array indexing.
Robbie Hatley's Perl Solution to The Weekly Challenge 252-1
Task 252-2: Unique Sum Zero Submitted by: Mohammad S Anwar You are given an integer, $n. Write a script to find an array containing $n unique integers such that they add up to zero. Example 1: Input: $n = 5 Output: (-7, -1, 1, 3, 4) Two other valid solutions are: (-5, -1, 1, 2, 3) and (-3, -1, 2, -2, 4). Example 2: Input: $n = 3 Output: (-1, 0, 1) Example 3: Input: $n = 1 Output: (0)
This is actually much simpler than Task 1, for a change. The following algorithm provides one valid solution (out of an always-infinite set of valid solutions) for each positive integer: Abort if $n is not a positive integer. Make an empty array @a. Push (1..int($n/2)) to @a. If $n is odd, push 0 to @a. Then push (-int($n/2)..-1) to @a. @a will now be $n elements long and will sum to 0, as the problem requires.
Robbie Hatley's Perl Solution to The Weekly Challenge 252-2
That's it for challenge 252; see you on challenge 253!
Comments
Post a Comment