The weekly challenge 272 - Task 2: String Score

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-272/#TASK2
 3 #
 4 # Task 2: String Score
 5 # ====================
 6 #
 7 # You are given a string, $str.
 8 #
 9 # Write a script to return the score of the given string.
10 #
11 ### The score of a string is defined as the sum of the absolute difference
12 ### between the ASCII values of adjacent characters.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "hello"
17 ## Output: 13
18 ##
19 ## ASCII values of characters:
20 ## h = 104
21 ## e = 101
22 ## l = 108
23 ## l = 108
24 ## o = 111
25 ##
26 ## Score => |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111|
27 ##       => 3 + 7 + 0 + 3
28 ##       => 13
29 #
30 ## Example 2
31 ##
32 ## Input: "perl"
33 ## Output: 30
34 ##
35 ## ASCII values of characters:
36 ## p = 112
37 ## e = 101
38 ## r = 114
39 ## l = 108
40 ##
41 ## Score => |112 - 101| + |101 - 114| + |114 - 108|
42 ##       => 11 + 13 + 6
43 ##       => 30
44 #
45 ## Example 3
46 ##
47 ## Input: "raku"
48 ## Output: 37
49 ##
50 ## ASCII values of characters:
51 ## r = 114
52 ## a = 97
53 ## k = 107
54 ## u = 117
55 ##
56 ## Score => |114 - 97| + |97 - 107| + |107 - 117|
57 ##       => 17 + 10 + 10
58 ##       => 37
59 #
60 ############################################################
61 ##
62 ## discussion
63 ##
64 ############################################################
65 #
66 # Split the string into an array of characters. Then start at
67 # index 1 and calculate the diff of the ASCII values of the
68 # character at the given index-1 and the given index, until the
69 # index reaches the index of the last element in the array. The
70 # ASCII value can be calculated by the ord() function, the absolute
71 # value of the diff will be revealed by the abs() function.
72 
73 use strict;
74 use warnings;
75 
76 string_score("hello");
77 string_score("perl");
78 string_score("raku");
79 
80 sub string_score {
81    my $str = shift;
82    print "Input: '$str'\n";
83    my @chars = split //, $str;
84    my $score = 0;
85    foreach my $i (1..$#chars) {
86       $score += abs(ord($chars[$i-1]) - ord($chars[$i]));
87    }
88    print "Output: $score\n";
89 }
90