Finding Local Maxima Over a Dynamic Range

前端 未结 6 2105
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 19:17

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

6条回答
  •  一整个雨季
    2020-12-14 19:29

    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;
    }
    

提交回复
热议问题