site.base_url }}/">The Bear's Den -->

The Bear's Den

Enter at your own risk

Split, Sort and Join

Task 1: Sort String

Submitted by: Mohammad Sajid Anwar


You are given a shuffle string, $str.

Write a script to return the sorted string.

A string is shuffled by appending word position to each word.

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"

Solution

This task can be solved by chaining some simple operations:

use strict;
use warnings;

sub sort_string {
    join " ",
    map $_->[0],
    sort {$a->[1] <=> $b->[1]}
    map [/(.+?)(\d+)$/],
    split /\s+/, shift;
}

See the full solution to task 1.

Task 2: Reverse Word

Submitted by: Mohammad Sajid Anwar


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 then DON’T do anything.

Example 1

Input: $str = "challenge", $char = "e"
Ouput: "acehllnge"

Example 2

Input: $str = "programming", $char = "a"
Ouput: "agoprrmming"

Example 3

Input: $str = "champion", $char = "b"
Ouput: "champion"

Solution

There is no need to restrict $char to one character. Substituting everything up to and including the given substring by itself - splitted, sorted and rejoined.

use strict;
use warnings;
use experimental 'signatures';

sub reverse_word ($str, $char) {

	$str =~ s#(.*?\Q$char\E)#join '', sort split //, $1#er;
}

See the full solution to task 2.


If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.