Finding Local Maxima Over a Dynamic Range

前端 未结 6 2103
伪装坚强ぢ
伪装坚强ぢ 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:40

    This function is O(n). It yields the results as it goes so it will also have very low memory overhead.

        public static IEnumerable FindPeaks(IEnumerable values, int rangeOfPeaks)
        {
            double peak = 0;
            int decay = 0;
    
            foreach (var value in values)
            {
                if (value > peak || decay > rangeOfPeaks / 2)
                {
                    peak = value;
                    decay = 0;
                }
                else
                {
                    decay++;
                }
    
                if (decay == rangeOfPeaks / 2)
                    yield return peak;
            }
        }
    

提交回复
热议问题