Peter’s blog ✴ Week 272 ✴ 3 June 2024
THE WEEKLY CHALLENGE
Fangs and strings
You are given a string, $str.
Write a script to return the score of the given string.
The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Example 1 Input: $str = 'hello' Output: 13 ASCII values of characters: h = 104 e = 101 l = 108 l = 108 o = 111 Score => |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| => 3 + 7 + 0 + 3 => 13 Example 2 Input: 'perl' Output: 30 ASCII values of characters: p = 112 e = 101 r = 114 l = 108 Score => |112 - 101| + |101 - 114| + |114 - 108| => 11 + 13 + 6 => 30 Example 3 Input: 'raku' Output: 37 ASCII values of characters: r = 114 a = 97 k = 107 u = 117 Score => |114 - 97| + |97 - 107| + |107 - 117| => 17 + 10 + 10 => 37
This is an easy one-liner:
($str =~ m|b(.*)| and $1 =~ m|^[^a]*$|) ? 'true' : 'false'
The first regular expression - $str =~ m|b(.*)| - looks for a 'b' and
the second - $1 =~ m|^[^a]*$| - checks for no 'a' in the part of the string follwing the first 'b':
note that the $1 refers to the matched substring from the first regular expression.
No gimmicks and just straight forward solutions in Perl with bonus DIY tool. Keep it up great work.
This review may cover either or both challenges for this week.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-06-03 use utf8; # Week 272 - task 2 - String score use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; string_score('hello'); string_score('supercalifragilisticexpialidocious'); string_score('The Weekly Challenge'); string_score('aĐbđcĒeēfĔgĕh🞱'); sub string_score { my ($score); $score += abs(ord(substr($_[0], $_, 1)) - ord(substr($_[0], $_ - 1, 1))) for 1 .. length($_[0]) - 1; say qq[\nInput: $_[0]\nOutput: $score]; }
6 lines of code
Input: hello Output: 13 Input: supercalifragilisticexpialidocious Output: 242 Input: The Weekly Challenge Output: 385 Input: aĐbđcĒeēfĔgĕh🞱 Output: 130928
Any content of this website which has been created by Peter Campbell Smith is in the public domain