Peter
Peter Campbell Smith

Tangled string
and drow

Weekly challenge 278 — 15 July 2024

Week 278: 15 Jul 2024

Task 2

Task — Reverse word

You are given a word, $word and a character, $char. Write a script to replace the substring up to and including $char with its characters sorted alphabetically. If the $char doesn’t exist in the word then don’t do anything.

Examples


Example 1
Input: $str = "challenge", $char = "e"
Output: "acehllnge"

Example 2
Input: $str = "programming", $char = "a"
Output: "agoprrmming"

Example 3
Input: $str = "champion", $char = "b"
Output: "champion"

Analysis

This could easily be a one-line answer by using an $a ? $b : $c construct, but for ease of understanding I've used if ($a) { $b } else { $c }.

Try it 

Try running the script with any input:



example: mushroom



example: r

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-07-15
use utf8;     # Week 278 - task 2 - Reverse word
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

reverse_word('challenge', 'e');
reverse_word('programming', 'a');
reverse_word('champion', 'b');
reverse_word('testing', 't');
reverse_word('multiplication', 'n');

sub reverse_word {
    
    my ($word, $char, $output);
    
    ($word, $char) = @_;
    if ($word =~ m|(.*?$char)(.*)|) {
        $output = join('', sort(split(//, $1))) . $2;
    } else {
        $output = $word;
    }
    
    printf(qq[\nInput:  \$word = '%s', \$char = '%s'\n], $word, $char);
    printf(qq[Output: '%s'\n], $output);
}

Output


Input:  $word = 'challenge', $char = 'e'
Output: 'acehllnge'

Input:  $word = 'programming', $char = 'a'
Output: 'agoprrmming'

Input:  $word = 'champion', $char = 'b'
Output: 'champion'

Input:  $word = 'testing', $char = 't'
Output: 'testing'

Input:  $word = 'multiplication', $char = 'n'
Output: 'aciiillmnopttu'

 

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