Peter
Peter Campbell Smith

Lead to Gold and 1 2 3

Weekly challenge 212 — 10 April 2023

Week 212 - 10 Apr 2023

Task 1

Task — Jumping letters

You are given a word having alphabetic characters only, and a list of positive integers of the same length. Write a script to print the new word generated after jumping forward each letter in the given word by the integer in the list. The given list would have the same number of integers as the number of letters in the given word.

Analysis

This is an exercise in using ord and chr. For each letter, we convert (ord) it to its ASCII value, subtract the ASCII value of 'a', add 26, take the result modulo 26, add back the ASCII for 'a', and chr the result.

The only slight complication is that upper and lower case letters are allowed, so we need to use ord('a') or ord('A') depending on the case of the supplied letter.

And so, like the Philosopher's Stone, we can turn Lead into Gold.

Try it 

Word: (example: Lead)

Shifts: (example: 21, 10, 11, 0)

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-04-10
use utf8;     # Week 212 task 1 - Jumping letters
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

advance_letters('Perl', [2, 22, 19, 9]);
advance_letters('Lead', [21, 10, 11, 0]);
advance_letters('Failure', [13, 20, 20, 17, 10, 1, 14]);

sub advance_letters {
    
    my (@letters, $j, $new, @jumps, $l, $ord_a);
    
    # input
    @letters = split('', $_[0]);
    @jumps = @{$_[1]};
    
    # loop over letters
    for $j (0 .. scalar @letters - 1) {
        $l = $letters[$j];
        
        # get offset - a or A
        $ord_a = ord($l) < ord('a') ? ord('A') : ord('a');
        
        # append jumped character
        $new .= chr((ord($l) - $ord_a + $jumps[$j]) % 26 + $ord_a);
    }
    
    # show result
    say qq[\nInput  \$word = '$_[0]' and \@jump = (] . join(', ', @jumps) . q[)];
    say qq[Output:        '$new'];
}
        

Output


Input  $word = 'Perl' and @jump = (2, 22, 19, 9)
Output:        'Raku'

Input  $word = 'Lead' and @jump = (21, 10, 11, 0)
Output:        'Gold'

Input  $word = 'Failure' and @jump = (13, 20, 20, 17, 10, 1, 14)
Output:        'Success'