Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #303 ("3-Digits Even" and "Delete and Earn")
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:
The Weekly Challenge for the week of 2024-01-06 through 2025-01-12 is #303.
The tasks for challenge #303 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 303-1: "3-Digits Even" Submitted by: Mohammad Sajid Anwar You are given a list (3 or more) of positive integers, @ints. Write a script to return all even 3-digits integers that can be formed using the integers in the given list. Example #1: Input: @ints = (2, 1, 3, 0) Output: (102, 120, 130, 132, 210, 230, 302, 310, 312, 320) Example #2: Input: @ints = (2, 2, 8, 8, 2) Output: (222, 228, 282, 288, 822, 828, 882)
This looks like yet another job for my favorite CPAN module, "Math::Combinatorics". I'll first extract the digits from @ints and push them to an array "@digits", then I'll grab all 3-combinations of @digits, then generate all permutations of each 3-combination, join, discard any beginning with 0, and discard any with odd final digit. Any that remain, I'll push to an array "@tde", then return a sorted, deduped copy of @tde.
Robbie Hatley's Perl Solution to The Weekly Challenge 303-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 303-2: "Delete and Earn" Submitted by: Mohammad Sajid Anwar You are given an array of integers, @ints. Write a script to return the maximum number of points you can earn by applying the following operation some number of times: Pick any ints[i] and delete it to earn ints[i] points. Afterwards, you must delete every element equal to (ints[i] - 1) and every element equal to (ints[i] + 1). Example #1: Input: @ints = (3, 4, 2) Output: 6 Delete 4 to earn 4 points. (Also delete all 3s and 5s.) Finally delete 2 to earn 2 points. Example #2: Input: @ints = (2, 2, 3, 3, 3, 4) Output: 9 Delete a 3 to earn 3 points. (Also delete all 2s and 4s.) Delete a 3 again to earn 3 points. Delete a 3 once more to earn 3 points.
Like most "minima" and "maxima" problems, this begs for recursion, so as to try all possibilities, seeking which yields minimum or maximum results. The trick is, whether/how to pass "results so far" to each recursive level. I think in this case, since we're finding a maximum within integer scores, I'll make a recursive subroutine "scores" that returns a list of all scores, then feed that list to the "max" function from CPAN module "List::Util".
Robbie Hatley's Perl Solution to The Weekly Challenge 303-2
That's it for challenge 303; see you on challenge 304!
Comments
Post a Comment