Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #327 (“Missing Integers” and “Minimum Absolute Difference”)

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-06-23 through 2025-06-29 is #327

The tasks for challenge #327 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 327-1: Missing Integers
Submitted by: Mohammad Sajid Anwar
You are given an array of n integers. Write a script to find all
the missing integers in the range 1..n in the given array.

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

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

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

To solve this, I use function "none" in CPAN module "List::Util" to determine which numbers of 1..n are equal to none of the elements of the array, then I return those numbers.

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 327-2: Minimum Absolute Difference
Submitted by: Mohammad Sajid Anwar
You are given an array of distinct integers. Write a script to
find all pairs of elements with minimum absolute difference
of any two elements.

Example 1
Input: @ints = (4, 1, 2, 3)
Output: [1,2], [2,3], [3,4]

Example 2
Input: @ints = (1, 3, 7, 11, 15)
Output: [1,3]

Example 3
Input: @ints = (1, 5, 3, 8)
Output: [1,3], [3,5]

I solve this by first sorting the array, then hashing all pairs by absolute value of difference. I determine minimum absolute value of difference by applying function "min" from CPAN module "List::Util" to the keys of the hash. Then I return those pairs corresponding to that hash key.

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

That's it for challenge 327; see you on challenge 328!

Comments

Popular posts from this blog

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #326 (“Day of Year” and “Decompressed List”)

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”)