首页 > 解决方案 > 如何识别浮点数组中的峰和谷?

问题描述

我有一个数组,

array = [
  0.43, 
  0.64, # => peak
  0.2, 
 -0.05, 
 -0.15, # => trough
  0.2, # => peak
 -0.1, 
 -0.5, # => trough
 -0.3
]

它在数据中有两个峰值和两个谷值。这些波峰和波谷不一定是数组的最小值最大值。我如何通过程序识别它们?

理想的输出是:

peak_indexes = [1, 5]
trough_indexes = [4, 7]

标签: arraysruby

解决方案


each_cons(3)提取检查中间项所需的相邻三个术语,同时排除中间具有第一个或最后一个元素的三元组array

with_index(1)考虑到中间第一个元素为的三元组被跳过的事实array,因此从 1 开始对索引进行编号。

您还没有定义高峰和低谷的含义。如果您的意思是取局部最大值和最小值,那么以下将起作用。

array.each_cons(3).with_index(1).select{|a, i| a.max == a[1]}.map(&:last)
# => [1, 5]

array.each_cons(3).with_index(1).select{|a, i| a.min == a[1]}.map(&:last)
# => [4, 7]

或者,如果您的意思是 Stefan 在我的回答的评论中解释的内容,那么以下内容将起作用:

array
.each_cons(3)
.with_index(1)
.select{|(a1, a2, a3), i| a1 < a2 && a2 > a3}
.map(&:last)
# => [1, 5]

array
.each_cons(3)
.with_index(1)
.select{|(a1, a2, a3), i| a1 > a2 && a2 < a3}
.map(&:last)
# => [4, 7]

推荐阅读