The weekly challenge 278 - Task 1: Sort String

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-278/#TASK1
 3 #
 4 # Task 1: Sort String
 5 # ===================
 6 #
 7 # You are given a shuffle string, $str.
 8 #
 9 # Write a script to return the sorted string.
10 #
11 ### A string is shuffled by appending word position to each word.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "and2 Raku3 cousins5 Perl1 are4"
16 ## Output: "Perl and Raku are cousins"
17 #
18 ## Example 2
19 ##
20 ## Input: $str = "guest6 Python1 most4 the3 popular5 is2 language7"
21 ## Output: "Python is the most popular guest language"
22 #
23 ## Example 3
24 ##
25 ## Input: $str = "Challenge3 The1 Weekly2"
26 ## Output: "The Weekly Challenge"
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # Split $str into words, then split each word into the word position
35 # and the actual word. Then sort this list by word position and
36 # add the words to the result.
37 
38 use strict;
39 use warnings;
40 
41 sort_string("and2 Raku3 cousins5 Perl1 are4");
42 sort_string("guest6 Python1 most4 the3 popular5 is2 language7");
43 sort_string("Challenge3 The1 Weekly2");
44 
45 sub sort_string {
46    my $str = shift;
47    my @words = split/\s+/, $str;
48    my $sorted = {};
49    print "Input: \"$str\"\n";
50    foreach my $word (@words) {
51       $word =~ s/(\d+)$//;
52       $sorted->{$1} = $word;
53    }
54    my $result = "";
55    foreach my $number (sort {$a <=> $b} keys %$sorted) {
56       $result .= "$sorted->{$number} ";
57    }
58    $result =~ s/\s+$//;
59    print "Output: \"$result\"\n";
60 }