Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #345 (“Peak Positions” and “Last Visitor”)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge
The Weekly Challenge for the week of 2025-10-27 through 2025-11-02 is #345. The tasks for challenge #345 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 345-1: Peak Positions Submitted by: Mohammad Sajid Anwar You are given an array of real numbers. Find all the peaks in the array. (A "peak" is an element that is strictly greater than its left and right neighbours.) Return the indices of all such peak positions. Example #1: Input: (1, 3, 2) Output: (1) Example #2: Input: (2, 4, 6, 5, 3) Output: (2) Example #3: Input: (1, 2, 3, 2, 4, 1) Output: (2, 4) Example #4: Input: (5, 3, 1) Output: () Example #5: Input: (1, 5, 1, 5, 1, 5, 1) Output: (1, 3, 5)
To solve this problem, I riffle through the middle indices using a ranged for loop, collect all "peak" indices found into an array, and return that array.
Robbie Hatley's Perl Solution to The Weekly Challenge 345-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 345-2: Last Visitor
Submitted by: Mohammad Sajid Anwar
You are given an array @ints of integers where each element is
either a positive integer or -1. We process the array from left
to right while maintaining two lists:
@seen (stores previously-seen positive integers, newest at front)
@ans (stores the answers for each -1)
Rules:
1. Iterate index $i from 0 to $#ints, strictly increasing.
2. If $ints[$i] is a positive integer, then insert it at the
front of @seen.
3. If $ints[$i] is -1, let $x be how many -1s in a row we’ve seen
before this one. If $x < len(@seen), append seen[$x] to @ans;
otherwise, append -1 to @ans.
4. At the end, return @ans.
Example #1: Input: (5, -1, -1)
Output: (5, -1)
@seen = (5)
First -1: @ans = (5)
Second -1: @ans = (5, -1)
Example #2: Input: (3, 7, -1, -1, -1)
Output: (7, 3, -1)
@seen = (7, 3)
First -1: @ans = (7)
Second -1: @ans = (7, 3)
Third -1: @ans = (7, 3, -1)
Example #3: Input: @ints = (2, -1, 4, -1, -1)
Output: (2, 4, 2)
Example #4: Input: @ints = (10, 20, -1, 30, -1, -1)
Output: (20, 30, 20)
Example #5: Input: @ints = (-1, -1, 5, -1)
Output: (-1, -1, 5)
This is just a matter of doing exactly what the description says. The logic is straightforward (if a bit perplexing) with no ambiguities, race conditions, or other entanglements, so this should be easy to program.
Robbie Hatley's Perl Solution to The Weekly Challenge 345-2
That's it for challenge 345; see you on challenge 346!
Comments
Post a Comment