arrays - 如何识别浮点数组中的峰和谷?
问题描述
我有一个数组,
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]
解决方案
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]
推荐阅读
- javascript - 如何将事件侦听器添加到画布上绘制的矩形?
- c# - 使用 SqlDataReader 从不同的结果集中读取数据
- sql-server - 我们可以在存储过程中根据某些条件添加多个更新语句吗
- mysql - 结合 ORDER BY FIELD 和另一个查询
- azure - Mac 上的 AzureAD Powershell
- python - 将 4 列合并为两列
- java - Java ArrayList 不断重复值直到数组结束
- ethereum - 如何为当前未知的合约编写合约调用?
- javascript - OnClick 将 php 文件加载到 HTML
- python - Django ORM不同的值按确定的日期有一个MySQL DB