Robbie Hatley's Solutions To The Weekly Challenge #249
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-12-24 through 2023-12-30) is weekly challenge #249. Its tasks are as follows:
Task 249-1: Equal Pairs Submitted by: Mohammad S Anwar Given an array of integers with even number of elements, write a script to divide the given array into equal pairs such that: a) Each element belongs to exactly one pair. b) The elements present in a pair are equal. Example 1: Input: @ints = (3, 2, 3, 2, 2, 2) Output: (2, 2), (3, 3), (2, 2) There are 6 elements in @ints. They should be divided into 6 / 2 = 3 pairs. @ints is divided into the pairs (2, 2), (3, 3), and (2, 2) satisfying all the conditions. Example 2: Input: @ints = (1, 2, 3, 4) Output: () There is no way to divide @ints 2 pairs such that the pairs satisfy every condition.
To solve this, I made a sub that splices integers from the array and attempts to make equal pairs. If every element can be paired, the sub will return the array of pairs; if not, it will return an empty array:
Robbie Hatley's Perl Solution to The Weekly Challenge 249-1
Task 249-2: DI String Match Submitted by: Mohammad S Anwar Given a string s, consisting of only the characters "D" and "I", find a permutation of the integers [0 .. length(s)] such that for each character s[i] in the string: s[i] == 'I' ⇒ perm[i] < perm[i + 1] s[i] == 'D' ⇒ perm[i] > perm[i + 1] Example 1: Input: $str = "IDID" Output: (0, 4, 1, 3, 2) Example 2: Input: $str = "III" Output: (0, 1, 2, 3) Example 3: Input: $str = "DDI" Output: (3, 2, 0, 1)
There's probably a "cute trick" way to do this, but I can't see what it is, and I'm not willing to waste hours this weekend trying to figure it out, so I'll use the "obvious" method instead: I'll use the permute() function from CPAN module Math::Combinatorics to make all possible permutations of 0..$length and return the first which meets the given requirements, or an empty array if the requirements cannot be met.
Addendum: I found that multiple valid answers exist for most compliant strings.
Robbie Hatley's Perl Solution to The Weekly Challenge 249-2
That's it for challenge 249 and the calendar year 2023; see you on challenge 250 in 2024! Happy New Year!
Comments
Post a Comment