Grouping consecutive numbers in an array

来源:互联网 发布:网络直播平台监管 编辑:程序博客网 时间:2024/05/21 19:34

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]]

it is possible to do this in a very compact way:

arr = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]arr.inject([]) { |a,e| (a[-1] && e == a[-1][-1] + 1) ? a[-1] << e : a << [e]; a }# [[1, 2, 3], [5], [7, 8, 9], [20, 21], [23], [29]]

Alternatively, starting with the first element to get rid of the a[-1] condition (needed for the case when a[-1] would be nil because a is empty):

arr[1..-1].inject([[arr[0]]]) { |a,e| e == a[-1][-1] + 1 ? a[-1] << e : a << [e]; a }

0 0
原创粉丝点击