Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #302 ("Ones and Zeros" and "Step by Step")
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-12-30 through 2025-01-05 is #302.
The tasks for challenge #302 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 302-1: "Ones and Zeros" Submitted by: Mohammad Sajid Anwar You are given an array of binary strings, @str, and two integers, $x and $y. Write a script to return the size of the largest subset of @str such that there are at most $x 0’s and $y 1’s in the subset. A set m is a subset of n if all elements of m are also elements of n. Example #1: Input: @str = ("10", "0001", "111001", "1", "0") $x = 5 $y = 3 Output: 4 The largest subset with at most five 0's and three 1's: ("10", "0001", "1", "0") Example #2: Input: @str = ("10", "1", "0") $x = 1 $y = 1 Output: 2 The largest subset with at most one 0's and one 1's: ("1", "0")
Since this problem's description mentions "subset", I'll assume that @str is required to be a "set" (that is, a collection of UNIQUE elements). I'll use my favorite CPAN module, "Math::Combinatorics", to create the power set of @str by collecting all "n choose m" combinations of all allowable m values (0..n). I'll then iterate through the power set looking for the largest which is within the given limits on 0s and 1s.
And since this problem's description speaks of $x and $y as being limits on number of 0s and 1s respectively, I'll assume that $x and $y must be non-negative integers.
Since this program will depend on the inputs being valid to work, I'll start by writing a "inputs_are_valid" subroutine (for checking inputs), then a "meets_criteria" subroutine (to determine if a given subset meets the given limits on 0s and 1s), then a "largest_subset" subroutine (which returns the largest subset meeting the given limits on 0s and 1s).
Robbie Hatley's Perl Solution to The Weekly Challenge 302-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 302-2: "Step by Step" Submitted by: Mohammad Sajid Anwar You are given an array of integers, @ints. Write a script to find the minimum positive start value such that step by step sum is never less than one. Example #1: Input: (-3, 2, -3, 4, 2) Output: 5 Example #2: Input: (1, 2) Output: 1 Example #3: Input: (1, -2, -3) Output: 5
The problem description, phrased mathematically, is "1 minus minimum partial sum starting at 0, or 1, whichever is greater".
Robbie Hatley's Perl Solution to The Weekly Challenge 302-2
That's it for challenge 302; see you on challenge 303!
Comments
Post a Comment