Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #322 (“String Format” and “Rank Array”)

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here:

The Weekly Challenge

The Weekly Challenge for the week of 2025-05-19 through 2025-05-25 is #322

The tasks for challenge #322 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 322-1: String Format
Submitted by: Mohammad Sajid Anwar
You are given a string and a positive integer. Write a script to
format the string, removing any dashes, in groups of size given
by the integer. The first group can be smaller than the integer
but should have at least one character. Groups should be
separated by dashes.

Example #1:
Input: $str = "ABC-D-E-F", $i = 3
Output: "ABC-DEF"

Example #2:
Input: $str = "A-BC-D-E", $i = 2
Output: "A-BC-DE"

Example #3:
Input: $str = "-A-B-CD-E", $i = 4
Output: "A-BCDE"

I first strip-out all the hypens, then calculate the "remainder" using modular arithmetic:
   remainder = length(string) % period
I then build an array of output chunks, the first chunk being the first "remainder" characters snipped from the left of the stripped string, then each additional chunk being the next "period" characters snipped from the left of the stripped string. Finally, I join all chunks together with "-" and return the result.

Robbie Hatley's Perl Solution to The Weekly Challenge 322-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 322-2: Rank Array
Submitted by: Mohammad Sajid Anwar
You are given an array of integers. Write a script to return an
array of the ranks of each element: the lowest value has rank 1,
next lowest rank 2, etc. If two elements are the same then they
share the same rank.

Example #1:
Input: @ints = (55, 22, 44, 33)
Output: (4, 1, 3, 2)

Example #2:
Input: @ints = (10, 10, 10)
Output: (1, 1, 1)

Example #3:
Input: @ints = (5, 1, 1, 4, 3)
Output: (4, 1, 1, 3, 2)

I solve this problem by first making a copy of the original array containing its numbers in numerically increasing order. Then I use a hash to record the "rank" of each number as I iterate through the numbers in increasing order. Then then I return a list of the "ranks" for the numbers in the original array.

Robbie Hatley's Perl Solution to The Weekly Challenge 322-2

That's it for challenge 322; see you on challenge 323!

Comments

Popular posts from this blog

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #317 (Theme: “Friendly Acronyms”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #319 (“Word Count” and “Minimum Common”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #318 (“Group Positions” and “Reverse Equals”)