Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #321 (“Distinct Average” and “Backspace Compare”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of taks each Monday. You can find it here:
The Weekly Challenge for the week of 2025-05-12 through 2025-05-18 is #321
The tasks for challenge #321 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 321-1: Distinct Average Submitted by: Mohammad Sajid Anwar You are given an array of numbers with even length. Write a script to return a count of distinct averages. The averages are calculated by removing the minimum and the maximum, then averaging the two. Example #1: Input: @nums = (1, 2, 4, 3, 5, 6) Output: 1 Step 1: Min = 1, Max = 6, Avg = 3.5 Step 2: Min = 2, Max = 5, Avg = 3.5 Step 3: Min = 3, Max = 4, Avg = 3.5 The count of distinct averages is 1. Example #2: Input: @nums = (0, 2, 4, 8, 3, 5) Output: 2 Step 1: Min = 0, Max = 8, Avg = 4 Step 2: Min = 2, Max = 5, Avg = 3.5 Step 3: Min = 3, Max = 4, Avg = 3.5 The count of distinct averages is 2. Example #3: Input: @nums = (7, 3, 1, 0, 5, 9) Output: 2 Step 1: Min = 0, Max = 9, Avg = 4.5 Step 2: Min = 1, Max = 7, Avg = 4 Step 3: Min = 3, Max = 5, Avg = 4 The count of distinct averages is 2.
After checking that each input array is, indeed, an even-length array of real numbers, I'll compute each "Min-Max Average" by doing the following:
- Put list in increasing numerical order.
- Loop while @sorted is not empty:
- Snip-off min and max.
- Compute next MMA ((min+max)/2) and push it to list @MMAs.
- Compute number of unique MMAs using "sort", "unique", and "scalar".

Robbie Hatley's Perl Solution to The Weekly Challenge 321-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 321-2: Backspace Compare Submitted by: Mohammad Sajid Anwar You are given two strings containing zero or more #. Write a script to return true if the two given strings are same by treating # as backspace. Example #1: Input: $str1 = "ab#c" $str2 = "ad#c" Output: true For first string, we remove "b" as it is followed by "#". For second string, we remove "d" as it is followed by "#". In the end both strings became the same. Example #2: Input: $str1 = "ab##" $str2 = "a#b#" Output: true Example #3: Input: $str1 = "a#b" $str2 = "c" Output: false
I'll solve this by simply doing what each "#" backspace character means: "erase this character, and the one to its left (if this is not the first character)". Then compare the processed strings.

Robbie Hatley's Perl Solution to The Weekly Challenge 321-2
That's it for challenge 321; see you on challenge 322!
Comments
Post a Comment