Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #304 ("Arrange Binary" and "Maximum Average")
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-13 through 2025-01-19 is #304.
The tasks for challenge #304 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 304-1: "Arrange Binary" Submitted by: Mohammad Sajid Anwar Reworded for clarity by Robbie Hatley. You are given a list @d of 0s and 1s and a positive integer $n. Write a script to return true if you can re-arrange the list by replacing at least $n "0" digits of @d with "1" in such a way that no two consecutive digits are 1, otherwise return false. Example #1: Input: @digits = (1, 0, 0, 0, 1), $n = 1 Output: true Re-arranged list: (1, 0, 1, 0, 1) Example #2: Input: @digits = (1, 0, 0, 0, 1), $n = 2 Output: false
First of all, @d needs to be checked to see if it already has any consecutive 1s; if so, return false. If not, then the number of 0s which can be converted to 1s is dependent purely on the sizes of the clusters of 0s, so I'll move through @d in a single pass left-to-right, changing all of the 0s to 1s which I can without creating consecutive 1s. If I was able to change at least $n 0s to 1s, I'll return true, else I'll return false.
Robbie Hatley's Perl Solution to The Weekly Challenge 304-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 304-2: "Maximum Average" Submitted by: Mohammad Sajid Anwar Reworded for clarity by Robbie Hatley. You are given an array @ints of integers and an integer $n which is less-than-or-equal-to the number of elements of @ints. Write a script to find the contiguous subarray of @ints of length $n which has the maximum average, then return that average. Example #1: Input: @ints = (1, 12, -5, -6, 50, 3), $n = 4 Output: 12.75 Subarray: (12, -5, -6, 50) Average: (12 - 5 - 6 + 50) / 4 = 12.75 Example #2: Input: @ints = (5), $n = 1 Output: 5
I'll use slices to make the subarrays, then use "sum0" from CPAN module "List::Util" to make the averages. I'll then just see which subarray has the greatest average.
Robbie Hatley's Perl Solution to The Weekly Challenge 304-2
That's it for challenge 304; see you on challenge 305!
Comments
Post a Comment