Peter
Peter Campbell Smith

Fangs and strings

Weekly challenge 272 — 3 June 2024

Week 272: 3 Jun 2024

Task 2

Task — String score

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.

Examples


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

Analysis

This is easily done in one line of code.

The task does specify ASCII, but at no extra cost we can include any Unicode characters, which gives us some larger scores.

Try it 

Try running the script with any input:



example: marmalade

Script


#!/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';

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];    
}

Output


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