检测红宝石重叠范围 [英] Detecting overlapping ranges in Ruby

查看:90
本文介绍了检测红宝石重叠范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有范围数组:

[[39600..82800], [39600..70200],[70200..80480]]

我要确定是否存在重叠或not.What是一个简单的方法来做到这一点的红宝石?

I need to determine if there is overlapping or not.What is an easy way to do it in ruby?

在上述情况下,输出应该是重叠。

In the above case the output should be 'Overlapping'.

推荐答案

这是一个非常有趣的益智,特别是如果你关心的演出。

This is a very interesting puzzle, especially if you care about performances.

如果范围只有两个,这是一个相当简单的算法,这也涉及到的 的ActiveSupport 重叠? 扩展。

If the ranges are just two, it's a fairly simple algorithm, which is also covered in ActiveSupport overlaps? extension.

def ranges_overlap?(r1, r2)
  r1.cover?(r2.first) || r2.cover?(r1.first)
end

如果要比较多个范围,这是一个相当有趣的算法锻炼。

If you want to compare multiple ranges, it's a fairly interesting algorithm exercise.

您可以遍历所有的范围,但你需要将每个范围比较所有其它的可能性,但是这是有成本指数的算法。

You could loop over all the ranges, but you will need to compare each range with all the other possibilities, but this is an algorithm with exponential cost.

一个更有效的解决方案是订购范围并执行二进制搜索,或者使用的数据结构(如树木),以使能够计算重叠

A more efficient solution is to order the ranges and execute a binary search, or to use data structures (such as trees) to make possible to compute the overlapping.

此问题也是在间隔树页面解释。本质上计算重叠包括寻找树木的交集。

This problem is also explained in the Interval tree page. Computing an overlap essentially consists of finding the intersection of the trees.

这篇关于检测红宝石重叠范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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