Robbie Hatley's Solutions To The Weekly Challenge #256

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 (2024-02-11 through 2024-02-17) is weekly challenge #256. Its tasks are as follows:

Task 256-1: Maximum Pairs
Submitted by: Mohammad Sajid Anwar
You are given an array of distinct words, @words. Write a script
to find the maximum pairs in the given array. The words $words[i]
and $words[j] can be a "pair" if one is reverse of the other.

Example 1:
Input: @words = ("ab", "de", "ed", "bc")
Output: 1
There is one pair in the given array: "de" and "ed"

Example 2:
Input: @words = ("aa", "ba", "cd", "ed")
Output: 0

Example 3:
Input: @words = ("uv", "qp", "st", "vu", "mn", "pq")
Output: 2

This problem is easily solved using a nested pair of 3-part loops which compare the fold-case of each word to the fold-case of the reverse of each word to its right; each time a match is found, increment a counter:

use v5.38;
# How many fwd/rev pairs are in @$words?
sub count_pairs ($words) {
   my $pair_count = 0;
   for    ( my $i =    0   ; $i <= $#$words - 1 ; ++$i ) {
      for ( my $j = $i + 1 ; $j <= $#$words - 0 ; ++$j ) {
         if ( fc $$words[$i] eq fc join '', reverse split //, $$words[$j] ) {
            ++$pair_count;
         }
      }
   }
   return $pair_count;
}

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

Task 256-2: Merge Strings
Submitted by: Mohammad Sajid Anwar
You are given two strings, $str1 and $str2. Write a script to
merge the given strings by adding in alternative order
starting with the first string. If a string is longer than the
other then append the remaining at the end.

Example 1:
Input: $str1 = "abcd", $str2 = "1234"
Output: "a1b2c3d4"

Example 2:
Input: $str1 = "abc", $str2 = "12345"
Output: "a1b2c345"

Example 3:
Input: $str1 = "abcde", $str2 = "123"
Output: "a1b2c3de"

I could roll my own on this, but why? This problem is already solved by the "mesh" function from CPAN module "List::Util", so I'll just use that. Doing otherwise would be like engineering and manufacturing my own electric car at a cost of 5G$ when I could have bought a Tesla for 50k$.

One caveat with List::Util::mesh, though, is that it inserts undefs into its output if its two input strings have unequal length. This can be got-around by using the "a//b" operator, which means "a if defined else b":

use v5.38;
use List::Util 'mesh';
sub merge_strings ($x, $y) {
   return join '', map {$_ // ''} mesh [split //, $x], [split //, $y];
}

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

That's it for challenge 256; see you on challenge 257!

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