Finding Local Maxima Over a Dynamic Range

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

    I suggest a few changes to Levy's post...

    1) Levy's code threw an exception when the specified values IList was a nearly straight line.

    2) I think the index of the peaks in the array is the desired result. Consider for example what would happen if we had two peaks with identical doubles? Ops. Changed to return index of peaks in specified IList.

        public static IList FindPeaks(IList values, int rangeOfPeaks)
        {
            List peaks = new List();
            double current;
            IEnumerable range;
    
            int checksOnEachSide = rangeOfPeaks / 2;
            for (int i = 0; i < values.Count; i++)
            {
                current = values[i];
                range = values;
    
                if (i > checksOnEachSide)
                {
                    range = range.Skip(i - checksOnEachSide);
                }
    
                range = range.Take(rangeOfPeaks);
                if ((range.Count() > 0) && (current == range.Max()))
                {
                    peaks.Add(i);
                }
            }
    
            return peaks;
        }
    

提交回复
热议问题