获取数字范围交叉点

时间:2011-03-22 12:08:21

标签: algorithm math

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

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

4 个答案:

答案 0 :(得分: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));
}

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

答案 1 :(得分: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 是您的“自定义”参数类型。您可以将它们设置为任何有效的有符号标量数字类型(int,float等)。使用#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位寻址),但是在减去单个天,分钟等时,您必须考虑进位和下溢。< / p>

答案 2 :(得分: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
    

答案 3 :(得分: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;
}
相关问题