Robbie Hatley's Solutions To The Weekly Challenge #282

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-08-11 through 2024-08-17 is #282. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 282-1: Good Integer
Submitted by: Mohammad Sajid Anwar
Write a script which, given a positive integer x with 3 or more
digits, returns the Good Integers within x (or -1 if none found),
where a "Good Integer" is a substring of x consisting of
exactly 3 identical digits (greedy match, left and right).
For example, in "2899467772", "777" is a "Good Integer"; but in
"28994677772", the string "777" is NOT a "Good Integer", even
though it appears in two places, because the substring of 7s is
4 digits long, not 3 digits.

Example 1:
Input: $int = 12344456
Output: "444"

Example 2:
Input: $int = 1233334
Output: -1 (because substring 3333 is 4 digits long, not 3)

Example 3:
Input: $int = 10020003
Output: "000"

I'll base the solution to this (and to 282-2) on the concept of "m//g operator in scalar context". Specifically, in 282-1 I'll check for a single-character match followed by 1-or-more copies of itself, then print all such matches which have length 3.

   use v5.36;
   sub good_ints ($x) {
      my @gi = ();
      while ($x =~ m/(.)\1+/g) {
         push @gi, $& if 3 == length $&
      }
      !@gi and push @gi, -1;
      @gi
   }

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 282-2: Changing Keys
Submitted by: Mohammad Sajid Anwar
Write a scripts which, given an alphabetic string $str, returns
the number of times a hunt-and-peck typist would have to move
his right forefinger to a new letter key in order to type the
string (not counting usages of shift keys).
Example 1:   Input: "pPeERrLl"   Output: 3
Example 2:   Input: "rRr"        Output: 0
Example 3:   Input: "GoO"        Output: 1

I'll base my solution to this (and also to 282-1) on the concept of "m//g operator in scalar context". Specifically, in 282-2 I'll check for two consecutive captured single-character matches (embedded in a positive look-ahead to prevent the matches from over-eating), then count the number of times that $1 ne $2.

   use v5.36;
   sub key_changes ($x) {
      my $f = fc $x;
      my $c = 0;
      while ($f =~ m/(?=(.)(.))/g) {
         $1 ne $2 and ++$c
      }
      $c
   }

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

That's it for challenge 282; see you on challenge 283!

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