A number of strings
Weekly challenge 358 — 26 January 2026
Week 358: 26 Jan 2026
You are given a string $str and an integer $int.
Write a script to encrypt the string using the algorithm - for each character $char in $str, replace $char with the $intth character after $char in the alphabet, wrapping if needed and return the encrypted string.
Example 1 Input: $str = 'abc', $int = 1 Output: 'bcd' Example 2 Input: $str = 'xyz', $int = 2 Output: 'zab' Example 3 Input: $str = 'abc', $int = 27 Output: 'bcd' Example 4 Input: $str = 'hello', $int = 5 Output: 'mjqqt' Example 5 Input: $str = 'perl', $int = 26 Output: 'perl'
This challenge starts with a string and produces an another string of the same length, where each character in the new string depends only on the character at the same position in the input string. I have therefore looped over the input characters to generate the output characters one by one.
The four lines of code within the loop could be merged into one, as seems to be fashionable in this forum, but I have left them separate to make the logic clear, which is:
$int), modulo 26,
The challenge doesn't state that $str only
contains lower-case characters, although it is
implied by the examples. One could clearly broaden
the solution to include upper-case letters, but beyond
that the definition of the encryption is undefined, so
I have assumed that we only need consider lower-case
letters.
Nor does it state that $int is positive,
but my solution works equally well if it is zero or
negative.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-01-26 use utf8; # Week 358 - task 2 - Encrypted string use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; encrypted_string('abc', 1); encrypted_string('xyz', 2); encrypted_string('abc', 27); encrypted_string('supercalifragilisticexpialidocious', 2601); encrypted_string('perl', 26); sub encrypted_string { my (@chars, $length, $shift, $encrypted, $j, $k); # initialise @chars = split('', lc($_[0])); $length = $#chars; $shift = $_[1]; $encrypted = ''; # encrypt for $j (0 .. $length) { $k = ord($chars[$j]) - ord('a'); $k = ($k + $shift) % 26; $k += ord('a'); $encrypted .= chr($k); } # report say qq[\nInput: \$str = '] . join('', @chars) . qq[', \$int = $shift]; say qq[Output: '$encrypted']; }
Input: $str = 'abc', $int = 1 Output: 'bcd' Input: $str = 'xyz', $int = 2 Output: 'zab' Input: $str = 'abc', $int = 27 Output: 'bcd' Input: $str = 'supercalifragilisticexpialidocious', $int = 2601 Output: 'tvqfsdbmjgsbhjmjtujdfyqjbmjepdjpvt' Input: $str = 'perl', $int = 26 Output: 'perl'
Any content of this website which has been created by Peter Campbell Smith is in the public domain