Robbie Hatley's Solutions To The Weekly Challenge #220

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

This week (2023-06-04 through 2023-06-10) is weekly challenge #220.

Task 1 is as follows:

"You are given a list of words. Write a script to return the list of common characters (sorted alphabetically) found in every word of the given list."

Now, that may sound simple, but that simplicity is partially derailed by the given examples:
Example 1: Input = ("Perl", "Rust", "Raku") Output = ("r")
Example 2: Input = ("love", "live", "leave") Output = ("e", "l", "v")
Do you see the problem? Right, the letter comparisons -- at least in the case of English-Language letters -- are being done case-insensitively.

My approach was to do the following for each array:

  1. Make a case-fold of a Unicode "fully-composed" normalization of the words of the original array.
  2. Make a sorted list of all unique characters appearing in the words of the "folded" array.
  3. Find which characters in the list appear in all of the words of the "folded" array.

The result was this:

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

Task 2 is as follows:

An array is "squareful" if the sum of every pair of adjacent elements is a perfect square. Given an array of integers, write a script to find all the permutations of the given array that are squareful.

I think Task 2 is actually easier than Task one this time. The only complication I see is that the examples appear to indicated that mathematically-different permutations are to be considered "the same" if they're visually identical:

Example 1:  Input = (1, 17, 8)  Output = ([1, 8, 17], [17, 8, 1])
( 1,  8, 17) since  1 + 8 ==  9 == 3^2 and 8 + 17 == 25 == 5^2.
(17,  8,  1) since 17 + 8 == 25 == 5^2 and 8 +  1 ==  9 == 3^2.

Example 2:  Input = (2, 2, 2)   Output = ([2, 2, 2])
( 2,  2,  2) since  2 + 2 = 4 = 2^2 and 2 + 2 = 4 = 2^2.

For example 2, the combinatorically-correct answer is actually ([2,2,2],[2,2,2],[2,2,2],[2,2,2],[2,2,2],[2,2,2]), becuase the left, middle, and right 2s are distinct. However, visually, it looks ridiculous, so I relented and used "uniq" from "List::Util" to get rid of visual duplicates. And as usual where combinations or permutations are involved, I used CPAN module "Math::Combinatorics" to cut programming time from one week down to about one hour. And I used five subroutines, to avoid spaghetti code and repetition, and to keep the main body of the program short:

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

That's it for 220; see you on 221!

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