【发布时间】:2011-03-22 12:08:20
【问题描述】:
除了这个问题Find number range intersection我想得到2个时间范围的交集范围。所以我的问题是
获取两个数字范围相交的时间范围的有效数学/算法方法是什么?
【问题讨论】:
-
你想要交集还是联合?
-
交叉路口抱歉(已编辑)
除了这个问题Find number range intersection我想得到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));
}
我今天很累.... ;-)
【讨论】:
这个伪 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 位寻址),但在减去个别天数、分钟数等时,您必须考虑进位和下溢。
【讨论】:
从第二个范围的每个端点中减去第一个范围的每个端点。如果你有:
所有结果都是 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
【讨论】:
如果有人需要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;
}
【讨论】: