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

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

问题描述

我想接受以下输入:

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

并将其转换为如下所示的内容:

and turn it into something like the following:

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

每个子数组代表一个整数范围.

Each sub-array represents a range of integers.

推荐答案

使用 Enumerable#chunk:

ranges = [1, 2, 4, 5, 6, 7, 9, 13]
  .enum_for(:chunk) # .chunk for Ruby >= 2.4
  .with_index { |x, idx| x - idx }
  .map { |_diff, group| [group.first, group.last] }

#=> [[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天全站免登陆