Peter
Peter Campbell Smith

Popular languages and
largest threefold

Weekly challenge 245 — 27 November 2023

Week 245 - 27 Nov 2023

Task 1

Task — Sort language

You are given two array of languages and their popularity. Write a script to sort the languages based on popularity.

Examples


Example 1
Input: @lang = ('perl', 'c', 'python')
       @popularity = (2, 1, 3)
Output: ('c', 'perl', 'python')

Example 2
Input: @lang = ('c++', 'haskell', 'java')
       @popularity = (1, 3, 2)
Output: ('c++', 'java', 'haskell')

Analysis

This task lends itself to the one-line solution, although in real life one would want to check that @popularity comprises precisely the set 1 .. $#popularity.

The ordered array required is
$order[$popularity[$j] - 1] == $languages[$j]

Try it 

Try running the script with any input:



example: 'c++', 'perl', 'python'



example: 3, 1, 2

Script


#!/usr/bin/perl

use v5.26;    # The Weekly Challenge - 2023-11-27
use utf8;     # Week 245 task 1 - Sort language
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

sort_language(['perl', 'c', 'python'], [2, 1, 3]);
sort_language(['perl', 'fortran', 'algol', 'pascal', 'html', 'apl', 'c++', 'French'],
    [7, 3, 5, 1, 8, 2, 4, 6]);
    
sub sort_language {
    
    my (@languages, @ranks, @order);
    
    @languages = @{$_[0]};
    @ranks = @{$_[1]};
    
    $order[$ranks[$_] - 1] = $languages[$_] for 0 .. @languages - 1;
    
    say qq[\nInput:      \@lang = ('] . join(q[', '], @languages) . q[')];
    say qq[      \@popularity = (] . join(', ', @ranks) . ')';
    say qq[Output:             ('] . join(q[', '], @order) . q[')];
}

Output


Input:      @lang = ('perl', 'c', 'python')
      @popularity = (2, 1, 3)
Output:             ('c', 'perl', 'python')

Input:      @lang = ('perl', 'fortran', 'algol', 'pascal', 'html', 'apl', 'c++', 'French')
      @popularity = (7, 3, 5, 1, 8, 2, 4, 6)
Output:             ('pascal', 'apl', 'fortran', 'c++', 'algol', 'French', 'perl', 'html')