Robbie Hatley's Solutions To The Weekly Challenge #238

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:

The Weekly Challenge

This week (2023-10-08 through 2023-10-14) is weekly challenge #238.

Task 238-1 is as follows:

Task 1: Running Sum
Submitted by: Mohammad S Anwar
Given an array of integers*, write a script to return the
running sum of the array. The running sum can be calculated as:
sum[i] = num[0] + num[1] + … + num[i].

*[RH Note: this can be done for ANY kind of addable numbers:
integer, real, complex, etc. For for the purpose of this script,
I'll assume all numbers are real (non necessarily integers).]

Example 1:
Input:  (1, 2, 3, 4, 5)
Output: (1, 3, 6, 10, 15)

Example 2:
Input:  (1, 1, 1, 1, 1)
Output: (1, 2, 3, 4, 5)

Example 3:
Input:  (0, -1, 1, 2)
Output: (0, -1, 0, 2)

This is what's known in mathematics as "the sequence of partial sums of a sequence of numbers", also known as a "series". A series can be formed for any sequence of addable numbers (integer, real, complex, etc), both finite and infinite. Some infinite serieses converge to an exact "limit" value; others diverge and have no limit. As for computation details, there are many ways to do it, all equivalent. I think I'll start by making an array "@series", then push $$aref[0] to it, then for each element of @$aref from index $idx = 1 onward, do "$series[$idx] = $series[$idx-1] + $$aref[$idx]":

Robbie Hatley's Solution to The Weekly Challenge 238-1

Task 238-2 is as follows:

Task 2: Persistence Sort
Submitted by: Mohammad S Anwar
Given an array of positive integers, write a script to sort the
array in increasing order with respect to the count of steps
required to obtain a single-digit number by multiplying its digits
recursively for each array element. If any two numbers have the
same count of steps, then print the smaller number first.

Example 1:
Input: @int = (15, 99, 1, 34)
Output: (1, 15, 34, 99)
15 => 1 x 5 => 5 (1 step)
99 => 9 x 9 => 81 => 8 x 1 => 8 (2 steps)
1  => 0 step
34 => 3 x 4 => 12 => 1 x 2 => 2 (2 steps)

Example 2:
Input: @int = (50, 25, 33, 22)
Output: (22, 33, 50, 25)
50 => 5 x 0 => 0 (1 step)
25 => 2 x 5 => 10 => 1 x 0 => 0 (2 steps)
33 => 3 x 3 => 9 (1 step)
22 => 2 x 2 => 4 (1 step)

This cries-out for the "sort compare @$aref" form of "sort". I'll combine both the "persistence" and "value" criteria in a single function called "by_persistence", then do this:
my @sorted = sort by_persistence @$aref;

Robbie Hatley's Solution to The Weekly Challenge 238-2

That's it for 238; see you on 239!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #221

Robbie Hatley's Solutions To The Weekly Challenge #239

Robbie Hatley's Solutions To The Weekly Challenge #262