Robbie Hatley's Solutions To The Weekly Challenge #245
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:
This week (2023-11-26 through 2023-12-02) is weekly challenge #245. Its tasks are as follows:
Task 245-1: Sort Language Submitted by: Mohammad S Anwar You are given two arrays: one of languages and the other of their popularities. Write a script to sort the languages based on their popularities. 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')
I tried solving this problem by "zipping" the two arrays together to make an array of [language, popularity] pairs, then sorting that array numerically by the second elements of the pairs; however, the resulting code was excessively verbose. But then I hit upon a much easier way: use an array slice! Take the indexes of the first array (0..$#$aref1), re-order them according to a sort of the second array, then "slice" the first array using the re-ordered indexes. The result was that I could now solve this entire problem with half a line of code:
Robbie Hatley's Perl Solution to The Weekly Challenge 245-1
Task 245-2: Largest of Three Submitted by: Mohammad S Anwar You are given an array of integers >= 0. Write a script to return the largest number formed by concatenating some of the given integers in any order which is also multiple of 3. Return -1 if none found. Example 1: Input: @ints = (8, 1, 9) Output: 981 981 % 3 == 0 Example 2: Input: @ints = (8, 6, 7, 1, 0) Output: 8760 Example 3: Input: @ints = (1) Output: -1
This problem is really just a matter of combinatorics, so I'll use CPAN module "Math::Combinatorics". But this time I'll use it's non-OOP functions, as OOP just isn't necessary for a problem like this and just gets in the way. I'll call my main sub "sub largest_of_three($aref)", which will find the largest multiple of 3 I can make by concatenting any permutation of any combination of integers from the input array, or return -1 if I can't make any divisible-by-three integers:
Robbie Hatley's Perl Solution to The Weekly Challenge 245-2
That's it for 245; see you on 246!
Comments
Post a Comment