如何编写一个参数,以捕获数字数组中的第一个非连续元素。到目前为止,我已经尝试使用each_cons方法,该方法在您在下面的代码中将看到的同理失败。我不知道该与什么结合。似乎没有太多关于如何实现此目标的文档,因此,如果您有任何建议,请务必分享。
这是我的代码当前的样子:
def first_non_consecutive(arr)
arr.each_cons(6) { |a| p a } # the block is just to test the output
end
期望的结果:
因此,例如,如果我有一个[1,2,3,4,6,7,8]序列,那么1则2则3则4都是连续的,但6不是连续的,所以这是第一个非连续数字。
当前结果:
Expected: 6, instead got: nil
Log
[1, 2, 3, 4, 5, 6] # => sequential array should return null2, would you recommend an if statement for this?
[2, 3, 4, 5, 6, 7] # => 6 is the first non-consecutive element
请注意,表达式也应能够采用负整数。
“不连续”是什么意思?
这意味着第一个数字加一个小于第二个数字,或者两个元素的差不是一个或…。有很多不同的表达方式。因此,您可以简单地搜索满足该条件的第一个元素:
arr.each_cons(2).find {|a, b| b - a != 1 }&.last
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句