区间以它们的边界作为数组a,b和x,y。我想计算它们之间交集的长度。根据这个页面:http://world.std.com/~swmcd/steven/tech/interval.html
我能看出来如果是0
(not (a < y && x < b)) 拿着。
例如,间隔1.2、4.3和2.1,5.5相交长度为4.3- 2.1 = 2.2。
发布于 2014-07-24 05:24:10
这样就行了。
码
def length(a,b,p)
[[a.last,b.last].min - [a.first,b.first].max,0].max.round(p)
end示例

发布于 2014-07-24 05:32:35
这是同一个问题的OO解决方案。我建议构建一个自定义的Interval类,但是这个实现只是一个例子,询问者应该考虑一下他的实际情况:
class Interval
attr_reader :range
def initialize range
@range = if range.nil? then nil else
fail TypeError, "Begin greater than end!" if range.begin > range.end
Range.new( range.begin, range.end )
end
end
def - other
begin
self.class.new [ range.begin, other.range.begin ].max ..
[ range.end, other.range.end ].min
rescue TypeError
self.class.new nil
end
end
def size
range.nil? ? 0 : range.end - range.begin
end
end
def Interval a, b # a convenience constructor
Interval.new a .. b
end
( Interval( 1.2, 4.3 ) - Interval( 2.1, 5.5 ) ).size
#=> 2.199999999999997发布于 2016-02-02 07:48:05
仅供参考-在MySQL卡的答案将是(没有四舍五入部分):
GREATEST( LEAST(`a_last`, `b_last`) - GREATEST(`a_first`, `b_first`), 0 )https://stackoverflow.com/questions/24925581
复制相似问题