Working in C#, I need to find all local peaks in a List of doubles and return them as another List doubles. This seems simple enough if I have a set number of values I\'m co
Using the Interactive Extensions package from the Rx team, you can solve this problem quite neatly. The package has a lot of functions to do with different buffering/windowing scenarios.
IEnumerable FindPeaks(IEnumerable numbers, int windowSize)
{
// Pad numbers to the left of so that the first window of is centred on the first item in
// Eg if numbers = { 1, 2, 3, 4 }, windowSize = 3, the first window should be { MinValue, 1, 2 }, not { 1, 2, 3 }
var paddedNumbers = Enumerable.Repeat(double.MinValue, windowSize / 2)
.Concat(numbers);
// Take buffers of size , stepping forward by one element each time
var peaks = paddedNumbers.Buffer(windowSize, 1)
.Select(range => range.Max())
.DistinctUntilChanged();
return peaks;
}