Robbie Hatley's Solutions To The Weekly Challenge #272

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-06-02 through 2024-06-08 is #272. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 272-1: Defang IP Address
Submitted by: Mohammad Sajid Anwar
You are given a valid IPv4 address. Write a script to return the
defanged version of the given IP address. A "defanged" IP address
replaces every period “.” with “[.]".

Example 1:
Input: $ip = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2:
Input: $ip = "255.101.1.0"
Output: "255[.]101[.]1[.]0"

The "s" operator makes quick work of this:

   sub defang ($x) {$x =~ s/\./[.]/gr}

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 272-2: String Score
Submitted by: Mohammad Sajid Anwar
You are given an ASCII string, $str. Write a script to return
the "score" of $str, where "score" is defined as the sum of
the absolute difference between the ASCII values of adjacent
characters.

Example 1:  Input: "hello"  Output: 13

Example 2:  Input: "perl"   Output: 30

Example 3:  Input: "raku"   Output: 37

This can easily be solved by using ord() and abs():

   sub  score ($x) {
      my @chars = split //, $x;
      my $score = 0;
      for ( my $idx = 0 ; $idx <= $#chars - 1 ; ++$idx ) {
         $score += abs(ord($chars[$idx])-ord($chars[$idx+1]));
      }
      return $score;
   }

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

That's it for challenge 272; see you on challenge 273!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #239

Robbie Hatley's Solutions To The Weekly Challenge #266