检查连续的数字 [英] Check for consecutive numbers

查看:158
本文介绍了检查连续的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组 M 。我正在寻找一种方法来检查 M 的元素是连续的。有没有一种方法来测试连续编号?

I have an array m of integers. I'm looking for a method to check if the elements of m are consecutive. Is there a way to test for consecutive numbers?

我想出了这个code意在工作的时候数组长度为4:

I came up with this code intended to work when the array length is four:

m.count == 4 && (m.max-m.min) == 3

这错误地返回真正 [1,1,1,4-] [0,0,0,3]

推荐答案

可枚举有一个名为的 each_cons 的工作原理是这样

Enumerable has a really handy method called each_cons that works like this:

[1,2,3,4].each_cons(2).to_a # => [ [1, 2], [2, 3], [3, 4] ]

这是它,它产生每个连续集的 N 的元素。在我们的例子的 N 的是2

That it, it yields each consecutive set of n elements. In our case n is 2.

当然,顾名思义,它返回一个枚举,所以我们可以与其他可枚举的方法,如所有IT连锁

Of course, as the name implies, it returns an Enumerator, so we can chain it with other Enumerable methods like all?:

def four_consecutive?(arr)
  return false unless arr.size == 4
  arr.each_cons(2).all? {|a, b| b == a + 1 }
end

four_consecutive?([2,3,4,5])   # => true
four_consecutive?([2,2,2,5])   # => false
four_consecutive?([1,2,3,4,5]) # => false

该方法具有上述别人的优点,因为呢?短路尽快块返回假的,它只会测试号码,直到找到一对不符合条件( b == A + 1 )。当然,只有四个元素这并不能真正有所作为,除非你的情况下调用此方法数千次,其中性能问题。

This method has the advantage above others that, because all? short-circuits as soon as the block returns false, it will only test numbers until it finds a pair that don't meet the condition (b == a + 1). Of course, with only four elements this doesn't really make a difference—unless you're calling this method thousands of times in situation where performance matters.

这篇关于检查连续的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆