我如何总结整数数组范围的数组?数组、整数、范围

由网友(口嚼泡泡糖)分享简介:我想借此输入,如:[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.e...

我想借此输入,如:

[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.

阅读全文

相关推荐

最新文章