我如何总结整数数组范围的数组? [英] How do I summarize array of integers as an array of ranges?

查看:161
本文介绍了我如何总结整数数组范围的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想借此输入,如:

[1,2,4,5,6,7,9,13]

和把它变成类似如下:

[[1,2],[4,7],[9,9],[13,13]]

每个子阵重新presents一个整数范围。

Each sub-array represents a range of integers.

推荐答案

使用功能的方法的可枚举#块的:

xs.enum_for(:chunk).with_index { |x, idx| x - idx }.map do |diff, group|
  [group.first, group.last]
end
# => [[1, 2], [4, 7], [9, 9], [13, 13]] 

它是如何工作:一旦索引,在数组中连续的元素具有相同的 X - IDX ,所以我们使用这个值来块(连续的项目组)的输入数组。最后,我们只需要把每个组建立对的第一个和最后一个元素。

How it works: once indexed, consecutive elements in the array have the same x - idx, so we use that value to chunk (grouping of consecutive items) the input array. Finally we just need to take the first and last elements of each group to build the pairs.

这篇关于我如何总结整数数组范围的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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