Peter’s blog ✴ Week 278 ✴ 15 July 2024

THE WEEKLY CHALLENGE
Tangled string and drow

The Perl Camel

Task 1

Sort string

You are given a shuffle string, $str. Write a script to return the sorted string. A string is shuffled by appending the word's position in the sorted string to each word.

Examples


Example 1
Input: $str = "and2 Raku3 cousins5 Perl1 are4"
Output: "Perl and Raku are cousins"

Example 2
Input: $str = "guest6 Python1 most4 the3 popular5 
   is2 language7"
Output: "Python is the most popular guest 
   language"

Example 3
Input: $str = "Challenge3 The1 Weekly2"
Output: "The Weekly Challenge"

Analysis

The guts of my solution is a single line.

I chop each input word into the alphabetic word $w and the numeric position $i and set $new[$i - 1] = $w. The solution is then a join of @new.

Perl Weekly’s review

from PW issue 678

DIY web interface with detailed analysis. Cool quality solutions every week.

This review may cover either or both challenges for this week.

Try it 

Try running the script with any input:



example: one3 this2 try1

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 1 - Sort string
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

sort_string('and2 Raku3 cousins5 Perl1 are4');
sort_string('A1 appending6 by5 each10 is3 position8 shuffled4 string2 to9 word7 word11');
sort_string('a3 challenge11 is2 line5 one4 solution6 Sort9 String10 the8 This1 to7');

sub sort_string {
    
    my ($string, @new);
    $string = shift;
    
    # new[$n - 1] is the $n'th word in the output string
    @new[$2 - 1] = $1 while $string =~ m|([a-z]+)(\d+)|gi;
    
    printf(qq[\nInput:  \@string = '%s'\n], $string);
    printf(qq[Output: '%s'\n], join(' ', @new));
}

6 lines of code

Output from script


Input:  @string = 'and2 Raku3 cousins5 Perl1 are4'
Output: 'Perl and Raku are cousins'

Input:  @string = 'A1 appending6 by5 each10 is3 position8
    shuffled4 string2 to9 word7 word11'
Output: 'A string is shuffled by appending word position
    to each word'

Input:  @string = 'a3 challenge11 is2 line5 one4 solution6
    Sort9 String10 the8 This1 to7'
Output: 'This is a one line solution to the Sort String 
    challenge'

 

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