The weekly challenge 380 - Task 2: Reverse Degree
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-380/#TASK2 3 # 4 # Task 2: Reverse Degree 5 # ====================== 6 # 7 # You are given a string. 8 # 9 # Write a script to find the reverse degree of the given string. 10 # 11 ## For each character, multiply its position in the reversed alphabet (‘a’ = 12 ## 26, ‘b’ = 25, …, ‘z’ = 1) with its position in the string. Sum these products 13 ## for all characters in the string to get the reverse degree. 14 # 15 ## Example 1 16 ## 17 ## Input: $str = "z" 18 ## Output: 1 19 ## 20 ## Reverse alphabet value of "z" is 1. 21 ## Position 1: 1 x 1 22 ## Sum of product: 1 23 # 24 ## Example 2 25 ## 26 ## Input: $str = "a" 27 ## Output: 26 28 ## 29 ## Reverse alphabet value of "a" is 26. 30 ## Position 1: 1 x 26 31 ## Sum of product: 26 32 # 33 ## Example 3 34 ## 35 ## Input: $str = "bbc" 36 ## Output: 147 37 ## 38 ## Reverse alphabet value of "b" is 25 and "c" is 24. 39 ## Position 1: 1 x 25 40 ## Position 2: 2 x 25 41 ## Position 3: 3 x 24 42 ## Sum of product: 25 + 50 + 72 => 147 43 # 44 ## Example 4 45 ## 46 ## Input: $str = "racecar" 47 ## Output: 560 48 ## 49 ## Reverse alphabet value of "r" is 9, "a" is 26, "c" is 24 and "e" is 24. 50 ## Position 1: 1 x 9 51 ## Position 2: 2 x 26 52 ## Position 3: 3 x 24 53 ## Position 4: 4 x 22 54 ## Position 5: 5 x 24 55 ## Position 6: 6 x 26 56 ## Position 7: 7 x 9 57 ## Sum of product: 9 + 52 + 72 + 88 + 120 + 156 + 63 58 # 59 ## Example 5 60 ## 61 ## Input: $str = "zyx" 62 ## Output: 14 63 ## 64 ## Reverse alphabet value of "z" is 1, "y" is 2 and "x" is 3. 65 ## Position 1: 1 x 1 66 ## Position 2: 2 x 2 67 ## Position 3: 3 x 3 68 ## Sum of product: 1 + 4 + 9 69 # 70 ############################################################ 71 ## 72 ## discussion 73 ## 74 ############################################################ 75 # 76 # We split the string into its individual characters. For the position, 77 # we just keep count. For the reverse alphabet value, we pick ord() of 78 # the character and remove 97 (which is the alphabet value in the range 79 # 0..25), then we remove the result from 26 to get the reverse alphabet 80 # value in the range 1..26. We then just need to multiply the position 81 # with the current value, then add the result to the sum. 82 83 use v5.36; 84 85 reverse_degree("z"); 86 reverse_degree("a"); 87 reverse_degree("bbc"); 88 reverse_degree("racecar"); 89 reverse_degree("zyx"); 90 91 sub reverse_degree($str) { 92 say "Input: \"$str\""; 93 my $pos = 0; 94 my $sum = 0; 95 foreach my $char (split //, $str) { 96 $pos++; 97 my $rev = 26 - (ord($char) - 97); 98 $sum += ($pos * $rev); 99 } 100 say "Output: $sum"; 101 }