Peter
Peter Campbell Smith

An odd character’s
nearly best word

Weekly challenge 255 — 5 February 2024

Week 255: 5 Feb 2024

Task 1

Task — Odd character

You are given two strings, $s and $t. The string $t is generated using the shuffled characters of the string $s with an additional character. Write a script to find the additional character in the string $t.

Examples


Example 1
Input: $s = "Perl" $t = "Preel"
Output: "e"

Example 2
Input: $s = "Weekly" $t = "Weeakly"
Output: "a"

Example 3
Input: $s = "Box" $t = "Boxy"
Output: "y"

Analysis

This is an easy one-liner: $t =~ s|$_|| for split('', $s); neatly delivers the result in $t.

However, it does assume that the task statement is accurate, that is, that there is precisely one added character. In a production environment I would check that there isn't more than one, or no, added character.

It also, arguably, isn't the most efficient answer because the s||| is repeatedly searching $t. That could (maybe) be improved by sorting the letters of both $s and $t, or by using an alternative mechanism that didn't involve repeatedly shifting the characters of $t leftwards.

But perhaps I am over-thinking this task.

Try it 

Try running the script with any input:



example: parallelogram



example: parallellogram

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-02-05
use utf8;     # Week 255 task 1 - Odd character
use strict;   # Peter Campbell Smith
use warnings; 
binmode STDOUT, ':utf8';

odd_character('Weekly', 'Weeakly');
odd_character('Perl', 'Preal');
odd_character('Box', 'Boxy');
odd_character('Five red baskets', 'abdee ezfik rsstv');

sub odd_character {
    
    # initialise
    my ($s, $t) = @_;
    say qq[\nInput:  \$s = '$s', \$t = '$t'];
    
    # do it
    $t =~ s|$_||i for split('', $s);
    say qq[Output: '$t'];
}

Output


Input:  $s = 'Weekly', $t = 'Weeakly'
Output: 'a'

Input:  $s = 'Perl', $t = 'Preal'
Output: 'a'

Input:  $s = 'Box', $t = 'Boxy'
Output: 'y'

Input:  $s = 'Five red baskets', $t = 'abdee ezfik rsstv'
Output: 'z'

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain