The weekly challenge 279 - Task 1: Sort Letters

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-279/#TASK1
 3 #
 4 # Task 1: Sort Letters
 5 # ====================
 6 #
 7 # You are given two arrays, @letters and @weights.
 8 #
 9 # Write a script to sort the given array @letters based on the @weights.
10 #
11 ## Example 1
12 ##
13 ## Input: @letters = ('R', 'E', 'P', 'L')
14 ##        @weights = (3, 2, 1, 4)
15 ## Output: PERL
16 #
17 ## Example 2
18 ##
19 ## Input: @letters = ('A', 'U', 'R', 'K')
20 ##        @weights = (2, 4, 1, 3)
21 ## Output: RAKU
22 #
23 ## Example 3
24 ##
25 ## Input: @letters = ('O', 'H', 'Y', 'N', 'P', 'T')
26 ##        @weights = (5, 4, 2, 6, 1, 3)
27 ## Output: PYTHON
28 #
29 ############################################################
30 ##
31 ## discussion
32 ##
33 ############################################################
34 #
35 # Merge the arrays into one so it's easier to sort, then
36 # concatenate the sorted characters
37 
38 use strict;
39 use warnings;
40 
41 sort_letters( ['R', 'E', 'P', 'L'], [3, 2, 1, 4] );
42 sort_letters( ['A', 'U', 'R', 'K'], [2, 4, 1, 3] );
43 sort_letters( ['O', 'H', 'Y', 'N', 'P', 'T'], [5, 4, 2, 6, 1, 3] );
44 
45 sub sort_letters {
46    my ($letters, $weights) = @_;
47    my @letters = @$letters;
48    print "Input: ('", join("', '", @$letters), "'), (", join(", ", @$weights), ")\n";
49    my @combined;
50    foreach my $i (0..$#letters) {
51       push @combined, [ $letters->[$i], $weights->[$i] ];
52    }
53    my $output = "";
54    foreach my $entry ( sort { $a->[1] <=> $b->[1] } @combined ) {
55       $output .= $entry->[0];
56    }
57    print "Output: $output\n";
58 }