Peaks
February 15, 2019
Given an array of integers, a peak is a subarray of minimal length in which the integer values increase and then decrease. For instance, in the array [5,5,4,5,4] there is a peak [4,5,4] and in the array [6,5,4,4,4,4,4,5,6,7,7,7,7,7,6] there is a peak [6,7,7,7,7,7,6]. Note that [4,5,6,7,7,7,7,7,6] shows a pattern of increasing and decreasing values, but it is not minimal because the first two items can be removed and the remaining subarray remains a peak. The array [5,5,5,5,4,5,4,5,6,7,8,8,8,8,8,9,9,8] has two peaks, [4,5,4] and [8,9,9,8].
Your task is to write a program that finds all of the peaks in an array. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Looks like a job for Regular Expressions:
By the way, what’s with the “This post is ad-supported” in the emails? Didn’t used to get them, they are quite annoying.
A Haskell version. We run-length encode the input lists so that we only have to look for three consecutive values that match the pattern low-high-low.
Here’s another Haskell solution. It uses a regex like my first solution, but since we don’t have regexs for arbitrary data types (don’t see why not), I’ve implemented simple regex matching as well:
Here’s a solution in C.
Example:
Here’s a solution in Python.
Output:
Here’s a slightly improved version of that regex matcher:
Here’s another Python solution.
Output:
In line 8 of my last post, I used the same name for both the list and the variable used to loop over the list. It seems to work, but was not my intent, arising from a renaming of variables.
Here’s the updated line 8.
@Daniel, glad someone had a prettier numpy solution!