排列成连续数字范围 [英] Array into ranges of consecutive numbers

查看:109
本文介绍了排列成连续数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个Ruby函数,将一个唯一数字数组转换为连续数字范围.

I am trying to make a Ruby function that converts an array of unique numbers into ranges of consecutive numbers.

[1, 2, 3, 5, 6, 8, 9] => [(1..3), (5..6), (8..9)]

这似乎并不难,但我想知道是否有更好的方法.

It doesn't seem too hard, but I want to know if there's better way.

推荐答案

这是一个解决方案.链接的代码比您需要的工作更多(数字不需要排序或连续),但是可以解决问题.或者,您可以使用@NewAlexandria建议的代码:

Here's a solution to the same question you're asking. The linked code does a bit more work than you require (the numbers don't need to be sorted, or consecutive), but it'll do the trick. Or, you could use this code, suggested by @NewAlexandria :

class Array
   def to_ranges
      compact.sort.uniq.inject([]) do |r,x|
         r.empty? || r.last.last.succ != x ? r << (x..x) : r[0..-2] << (r.last.first..x)
      end
   end
end

这篇关于排列成连续数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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