1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-212/#TASK1
 3 #
 4 # Task 1: Jumping Letters
 5 # =======================
 6 #
 7 # You are given a word having alphabetic characters only, and a list of
 8 # positive integers of the same length
 9 #
10 # Write a script to print the new word generated after jumping forward each
11 # letter in the given word by the integer in the list. The given list would
12 # have exactly the number as the total alphabets in the given word.
13 #
14 ## Example 1
15 ##
16 ## Input: $word = 'Perl' and @jump = (2,22,19,9)
17 ## Output: Raku
18 ##
19 ## 'P' jumps 2 place forward and becomes 'R'.
20 ## 'e' jumps 22 place forward and becomes 'a'. (jump is cyclic i.e. after 'z' you go back to 'a')
21 ## 'r' jumps 19 place forward and becomes 'k'.
22 ## 'l' jumps 9 place forward and becomes 'u'.
23 #
24 ## Example 2
25 ##
26 ## Input: $word = 'Raku' and @jump = (24,4,7,17)
27 ## Output: 'Perl'
28 #
29 ############################################################
30 ##
31 ## discussion
32 ##
33 ############################################################
34 #
35 # Going character by character, apply the jump. Just check if we
36 # are in a lower- or uppercase character first to jump in the
37 # right space.
38 
39 use strict;
40 use warnings;
41 
42 jumping_letters("Perl", [2,22,19,9]);
43 jumping_letters("Raku", [24,4,7,17]);
44 
45 sub jumping_letters {
46    my ($word, $jump) = @_;
47    my @chars = split //, $word;
48    my $result;
49    print "Input: $word - [" . join(",", @$jump) . "]\n";
50    foreach my $i (0..$#chars) {
51       $result .= jumping_letter($chars[$i], $jump->[$i]);
52    }
53    print "Output: $result\n";
54 }
55 
56 # jump a single letter
57 sub jumping_letter {
58    my ($chr, $jump) = @_;
59    my $o = ord($chr);
60    if(65 <= $o && $o <= 90) {
61       # uppercase letter
62       $o += $jump || 0;
63       # we need to wrap around since we
64       # jumped past "Z"
65       if($o > 90) {
66          $o -= 26;
67       }
68       return chr($o);
69    } else {
70       # lowercase character
71       $o += $jump || 0;
72       # we need to wrap around since we
73       # jumped past "z"
74       if($o > 122) {
75          $o -= 26;
76       }
77       return chr($o);
78    }
79 }
80