2011-03-22 102 views
1

除了这个问题Find number range intersection我想获得2个时间范围的交集范围。所以我的问题是获取号码范围交集

什么是有效的数学/算法的方式来获得两个数字范围的交集的时间范围?

+0

你想要的路口或工会? – 2011-03-22 12:50:42

+0

十字路口对不起(编辑后) – 2011-03-22 12:58:09

回答

2
public BTraceStatsTimeRange getOverlap(BTraceStatsTimeRange other) { 
    if (!intersect(other)) { 
     return NULL; 
    } 
    long startOther = other.start; 
    long endOther = other.end; 
    long minEnd = Math.min(end, endOther); 
    long maxStart = Math.max(start, startOther); 
    return new BTraceStatsTimeRange(Math.min(minEnd, maxStart), Math.max(
      minEnd, maxStart)); 
} 

今天我累了.... ;-)

0

从第二范围的每个端点减去第一范围的每个端点。如果您有:

  • 所有的阳性或阴性结果:范围是不相交的
  • 一个非负或从负的结果:该路口是这个结果
  • 两个非阴性结果的操作数:范围在这两种计算非共同操作
  • 所有结果都是0:最简并的范围不断

    vectors = (
        ((1, 3), (2, 4), '2-3'), 
        ((1, 4), (2, 3), '2-3'), 
        ((1, 2), (3, 4), 'Disjoint'), 
        ((2, 4), (1, 3), '2-3'), 
        ((2, 3), (1, 4), '2-3'), 
        ((3, 4), (1, 2), 'Disjoint'), 
    ) 
    
    for a, b, c in vectors: 
        print c, a, b 
        for x in a: 
        for y in b: 
         print x, y, x-y 
    
2

这个伪-C应该做的伎俩:

R_TYPE Intersection(P_TYPE start1, P_TYPE start2, P_TYPE end1, P_TYPE end2) 
{ 

    if(max(start1, start2) <= min(end1, end2)) 
    { 
     return(min(end1, end2) - max(start1, start2)); 
    } 

    return(DISJOINT); 
} 

R_TYPE是你的 '自定义' 返回类型,P_TYPE是您的'自定义'参数类型。你可以将其设置为任何有效的标签号码类型(整数,浮点等)使用#define DISJOINT ...DISJOINT设置为某个值,通常会超出范围(-1或MAX_INT等)

如果你有一些自定义DATE_TIME_TYPE,你必须改变这个以适应这个。举例来说,如果你定义诸如结构:

typedef union 
{ 
    unsigned char date_time[7]; 
    struct 
    { 
     unsigned char second; 
     unsigned char minute; 
     unsigned char hour; 
     unsigned char day; 
     unsigned char month; 
     unsigned int year; 
    } 
}DATE_TIME_TYPE; 

您可能仍然能够通过做值之间的直接比较,以获得(假设小尾数和8位寻址),但你必须要考虑便于携带和下溢减去各天,分钟的时候,等

0

如果有人需要JavaScript版本是在这里:

function findRangeIntersection(a1, a2, b1, b2) { 
    if (Math.max(a1, b1) <= Math.min(b2, a2)) { 
     return Math.min(a2, b2) - Math.max(a1, b1); 
    } 
    return Number.NaN; 
}