如何在数字数组中找到前两个连续的元素? [英] How do I find the first two consecutive elements in my array of numbers?
本文介绍了如何在数字数组中找到前两个连续的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,使用Ruby 2.4,我有一组唯一的,有序的数字
Using Ruby 2.4, I have an array of unique, ordered numbers, for example
[1, 7, 8, 12, 14, 15]
如何找到前两个元素的差为1?例如,上面的数组的答案是"7"和"8".
How do I find the first two elements whose difference is 1? For example, the above array the answer to that is "7" and "8".
推荐答案
您可以使用each_cons
和find
从对数组中获取第一个元素,其中第二个元素减去第一个元素等于1:
You could use each_cons
and find
to get the first element from the array of pairs where the second element less the first one is equal to 1:
p [1, 7, 8, 12, 14, 15].each_cons(2).find { |a, b| b - a == 1 }
# => [7, 8]
这篇关于如何在数字数组中找到前两个连续的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文