Robbie Hatley's Solutions To The Weekly Challenge #279

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

The Weekly Challenge for the week of 2024-07-21 through 2024-07-27 is #279. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 279-1: Sort Letters
Submitted by: Mohammad Sajid Anwar
Given two arrays, @letters and @weights, write a script to sort
@letters based on @weights.

Example 1:
Input: @letters = ('R', 'E', 'P', 'L')
       @weights = (3, 2, 1, 4)
Output: PERL

Example 2:
Input: @letters = ('A', 'U', 'R', 'K')
       @weights = (2, 4, 1, 3)
Output: RAKU

Example 3:
Input: @letters = ('O', 'H', 'Y', 'N', 'P', 'T')
       @weights = (5, 4, 2, 6, 1, 3)
Output: PYTHON

I use List::MoreUtils::Zip6 to make a list of [letter, weight] pairs, sort those pairs by weight, then return a join of the letters of the sorted list:

   use v5.36;
   use List::MoreUtils 'zip6';
   sub sort_letters ($letters, $weights) {
      join '',
      map {$$_[0]}
      sort {$$a[1]<=>$$b[1]}
      zip6 @$letters, @$weights;
   }

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 279-2: Split String
Submitted by: Mohammad Sajid Anwar
Given a string $str, write a script to split $str into two
strings, each containing exactly same number of vowels.
Return true if you can, otherwise return false.

Example 1:
Input: $str = "perl"
Ouput: false

Example 2:
Input: $str = "book"
Ouput: true

Example 3
Input: $str = "good morning"
Ouput: true

I don't even bother actually splitting strings, since we're only interested in whether the number of vowels is even. So I make two subs, "count_vowels" and "can_split", which do as their names suggest. The only tricky part is defining what a "vowel" is. For the purposes of this exercise I'll define a "vowel" to be any of [aeiouAEIOU] with-or-without combining marks.:

   use v5.36;
   use Unicode::Normalize 'NFD';
   sub count_vowels ($string) {scalar map {$_} NFD($string) =~ m/[aeiouAEIOU]/g}
   sub can_split ($string) {(0==count_vowels($string)%2)?"true":"false"}

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

That's it for challenge 279; see you on challenge 280!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #266

Robbie Hatley's Solutions To The Weekly Challenge #273