Robbie Hatley's Solutions To The Weekly Challenge #237
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle, usually with two parts, cycling every Sunday. You can find it here:
This week (2023-10-01 through 2023-10-07) is weekly challenge #237.
Task 1 is as follows:
Task 1: Seize The Day Submitted by: Mark Anderson Given a year, a month, a weekday of month, and a day of week (1 (Mon) .. 7 (Sun)), print the day. Example 1: Input: Year = 2024, Month = 4, Weekday of month = 3, day of week = 2 Output: 16 The 3rd Tue of Apr 2024 is the 16th Example 2: Input: Year = 2025, Month = 10, Weekday of month = 2, day of week = 4 Output: 9 The 2nd Thu of Oct 2025 is the 9th Example 3: Input: Year = 2026, Month = 8, Weekday of month = 5, day of week = 3 Output: 0 There isn't a 5th Wed in Aug 2026
I am soooooo not going to pull in all of the heavy artillery from my "day-of-week.pl" script; it's just not needed for this. I'll use "use Time::Local 'timelocal_modern';" and "localtime" instead, and I'll use this algorithm:
- Start with day-of-month set to zero, then enter this loop:
- Loop while dow-counter < weekday-of-month, else skip to step 9 below.
- Increment day-of-month.
- If day-of-month is now invalid, set it to 0 and exit loop.
- Get seconds-since-epoch for current day-of-month (using "timelocal_modern")
- Get current-day-of-week from seconds-since-epoch (using "localtime")
- Increment dow-counter if current dow == target dow.
- Loop back to step 2.
- Print results.
The script I came up with was this:
Robbie Hatley's Solution to The Weekly Challenge 237-1
Task 2 is as follows:
Task 2: Maximize Greatness Submitted by: Mohammad S Anwar You are given an array of integers. Write a script to permute the given array such that you get the maximum possible "greatness". To determine "greatness", nums[i] < perm[i] where 0 ≤ i < nums.length Example 1: Input: @nums = (1, 3, 5, 2, 1, 3, 1) Output: 4 One possible permutation: (2, 5, 1, 3, 3, 1, 1) which returns 4 greatness as below: nums[0] < perm[0] nums[1] < perm[1] nums[3] < perm[3] nums[4] < perm[4] Example 2: Input: @ints = (1, 2, 3, 4) Output: 3 One possible permutation: (2, 3, 4, 1) which returns 3 greatness as below: nums[0] < perm[0] nums[1] < perm[1] nums[2] < perm[2]
I've no time to re-invent yet-another array-permutations subroutine this weekend so I'll use CPAN module "Math::Combinatorics", which has come to my aid in so many of these weekly challenges. Then it's just a matter of checking the "greatness" of every possible permutation of a given array and keeping track of "maximum greatness found so far".
The script I ended up with is this:
Robbie Hatley's Solution to The Weekly Challenge 237-2
That's it for 237; see you on 238!
Comments
Post a Comment