在数组分组连续号码 [英] Grouping consecutive numbers in an array

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

问题描述

我需要连续号码添加到一个新的数组,如果它不是一个连续的号码,只有值添加到一个新的数组:

I need to add consecutive numbers to a new array and, if it is not a consecutive number, add only that value to a new array:

old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]

我要得到这样的结果:

I want to get this result:

 new_array = [
  [1,2,3],
  [5],
  [7,8,9]
  [20,21]
  [23],
  [29]
]

有没有更简单的方法来做到这一点?

Is there an easier way to do this?

推荐答案

这是在的的RDoc (略有修改):

This is the official answer given in RDoc (slightly modified):

actual = old_array.first
old_array.slice_before do
  |e|
  expected, actual = actual.next, e
  expected != actual
end.to_a

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

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