The weekly challenge 245 - Task 1: Sort Language

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-245/#TASK1
 3 #
 4 # Task 1: Sort Language
 5 # =====================
 6 #
 7 # You are given two array of languages and its popularity.
 8 #
 9 # Write a script to sort the language based on popularity.
10 # Example 1
11 #
12 # Input: @lang = ('perl', 'c', 'python')
13 #        @popularity = (2, 1, 3)
14 # Output: ('c', 'perl', 'python')
15 #
16 # Example 2
17 #
18 # Input: @lang = ('c++', 'haskell', 'java')
19 #        @popularity = (1, 3, 2)
20 # Output: ('c++', 'java', 'haskell')
21 #
22 ############################################################
23 ##
24 ## discussion
25 ##
26 ############################################################
27 #
28 # The solution that jumps right into my face is to fill the data
29 # into a hash table, using lang as the key and popularity as the
30 # value. Then sort the keys by their values and put the result into
31 # the output.
32 
33 use strict;
34 use warnings;
35 
36 sort_language( ['perl', 'c', 'python'], [2, 1, 3] );
37 sort_language( ['c++', 'haskell', 'java'], [1, 3, 2] );
38 
39 sub sort_language {
40    my ($lang, $popularity) = @_;
41    print "Input: (" . join(", ", @$lang) . ")\n       (" . join(", ", @$popularity) . ")\n";
42    my $hash = {};
43    my $index = 0;
44    foreach my $elem (@$lang) {
45       $hash->{$elem} = $popularity->[$index];
46       $index++;
47    }
48    print "Output: (" . join(", ", sort { $hash->{$a} <=> $hash->{$b} } keys %$hash) . ")\n";
49 }
50