我正在寻找一种在Java中表示一组支持mathematical sets操作(联合,交集等)的独立时间段的方法。
请注意,我期望作为此类操作结果的集合将合并为连续时间段(尽可能多)。
示例:
假设我有两个假设集:
// imaginary constructor. numbers are unix times
TimeSet a = [(0,2), (3,6)];
TimeSet b = [(1,4), (5,7)];
现在让我们对它们执行一些操作:
a.union(b); // result = [(0,7)]
a.minus(b); // result = [(0,1), (4,5)]
b.minus(a); // result = [(2,3), (6,7)]
a.intersect(b); // result = [(1,2), (3,4), (5,6)]
a.diff(b); // result = [(0,1), (2,3), (4,5), (6,7)]
答案 0 :(得分:0)
我发现的最好的是JodaTime的能力。
http://joda-time.sourceforge.net/apidocs/org/joda/time/Interval.html
该间隔允许使用" abuts"," gap"和"重叠"等方法,这可能需要额外的条件算法。
答案 1 :(得分:0)
由于缺乏对Java中此类间隔功能的一般支持,我决定使用我的库Time4J实现它:
Moment d0 = Moment.of(0, TimeScale.POSIX);
Moment d1 = Moment.of(1, TimeScale.POSIX);
Moment d2 = Moment.of(2, TimeScale.POSIX);
Moment d3 = Moment.of(3, TimeScale.POSIX);
Moment d4 = Moment.of(4, TimeScale.POSIX);
Moment d5 = Moment.of(5, TimeScale.POSIX);
Moment d6 = Moment.of(6, TimeScale.POSIX);
Moment d7 = Moment.of(7, TimeScale.POSIX);
MomentInterval i1 = MomentInterval.between(d0, d2);
MomentInterval i2 = MomentInterval.between(d3, d6);
IntervalCollection<Moment> a = IntervalCollection.onMomentAxis().plus(i1).plus(i2);
MomentInterval i3 = MomentInterval.between(d1, d4);
MomentInterval i4 = MomentInterval.between(d5, d7);
IntervalCollection<Moment> b = IntervalCollection.onMomentAxis().plus(i3).plus(i4);
System.out.println(a.plus(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:02Z),[1970-01-01T00:00:01Z/1970-01-01T00:00:04Z),[1970-01-01T00:00:03Z/1970-01-01T00:00:06Z),[1970-01-01T00:00:05Z/1970-01-01T00:00:07Z)}
System.out.println(a.union(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:07Z)}
System.out.println(a.minus(b));
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:01Z),[1970-01-01T00:00:04Z/1970-01-01T00:00:05Z)}
System.out.println(b.minus(a));
// {[1970-01-01T00:00:02Z/1970-01-01T00:00:03Z),[1970-01-01T00:00:06Z/1970-01-01T00:00:07Z)}
System.out.println(a.intersect(b));
// {[1970-01-01T00:00:01Z/1970-01-01T00:00:02Z),[1970-01-01T00:00:03Z/1970-01-01T00:00:04Z),[1970-01-01T00:00:05Z/1970-01-01T00:00:06Z)}
System.out.println(a.xor(b)); // your diff operator
// {[1970-01-01T00:00:00Z/1970-01-01T00:00:01Z),[1970-01-01T00:00:02Z/1970-01-01T00:00:03Z),[1970-01-01T00:00:04Z/1970-01-01T00:00:05Z),[1970-01-01T00:00:06Z/1970-01-01T00:00:07Z)}