【发布时间】:2019-05-07 03:10:38
【问题描述】:
如果我有一个数组:
array = [1,2,2,2,2,5,5,1,1,1,3,3,3,3,2,2,2,2,2,2,2]
我希望能够识别长度大于 3 的连续匹配数字。并映射连续数字的起始索引。上述数组的示例输出为:
consecutive_numbers = [
{starting_index: 1, value: 2, length: 4},
{starting_index: 10, value: 3, length: 4},
{starting_index: 14, value: 2, length: 7}
]
值可以相同,但连续序列'必须互斥。看到有2个值为2的hash,但是它们的起始索引不同。
到目前为止我的尝试......看起来像这样:
array.each_cons(3).with_index.select{|(a,b,c), i|
[a,b,c].uniq.length == 1
}
但这会返回:
[[[2, 2, 2], 1], [[2, 2, 2], 2], [[1, 1, 1], 7], [[3, 3, 3], 10], [[3, 3, 3], 11], [[2, 2, 2], 14], [[2, 2, 2], 15], [[2, 2, 2], 16], [[2, 2, 2], 17], [[2, 2, 2], 18]]
但这会返回重叠的结果。
【问题讨论】:
-
你自己有没有尝试过?
-
@Loocid 是的,感谢您的提问,我已将其添加到问题中
标签: ruby-on-rails arrays ruby