检查整数数组中的红宝石递增 [英] Check if array of integers increments in Ruby

查看:107
本文介绍了检查整数数组中的红宝石递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查如果一旦分类由1递增是一个数组值

I want to check if an arrays values once sorted are incrementing by 1

例如

[1, 2, 3, 4, 5] = TRUE
[1, 2, 8, 9, 10] = FALSE

任何建议都多少AP preciated

Any suggestions are much appreciated

推荐答案

试试这个:

def array_increments_by?(step, array)
  sorted = array.sort
  lastNum = sorted[0]
  sorted[1, sorted.count].each do |n|
    if lastNum + step != n
      return false
    end
    lastNum = n
  end
  true
end

用法:

array_increments?(1, [0,1,2,3]) #=> true
array_increments?(2, [0,2,4,6]) #=> true
array_increments?(2, [0,2,4,8]) #=> false

这篇关于检查整数数组中的红宝石递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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