有没有简单的方法来定义两个数字对的重叠范围? 例如, Pair1 = [360,780] Pair2 = [420,800]
答案是[420,780]
答案 0 :(得分:3)
确保您的间隔重叠。
然后取两个对的下限的最大值和上限的最小值。
int lower = Math.max(myPair1.x1, myPair2.x1);
int upper = Math.min(myPair1.x2, myPair2.x2);
if(lower < upper)
return new Pair(lower, upper)
else
throw new CustomException("Intervals not overlap")
答案 1 :(得分:1)
我会创建一个类似
的类class Range {
final int start;
final int end;
private Range(int start; int end) { this.start = start; this.end = end; }
public static Range of(int start, int end) { return new Range(start, end); }
public Range and(Range r) {
return new Range(Math.max(start, r.start), Math.min(end, r.end);
}
}
你可以写
Range one = Range.of(360, 780);
Range two = Range.of(420, 800);
Range both = one.and(two);
答案 2 :(得分:0)
这个怎么样:
int from = Math.max(pair1.getX(), pair2.getX());
int to = Math.min(pair1.getY(), pair2.getY());
if (from <= to) {
return new Pair(from, to);
} else {
return null;
}
答案 3 :(得分:0)
有点滥用java.awt.geom
,请尝试:
public static double[] createIntersection(double[] a1, double[] a2) {
Rectangle2D r1 = new Rectangle2D.Double(), r2 = new Rectangle2D.Double();
r1.setFrameFromDiagonal(a1[0], 0, a1[1], 1);
r2.setFrameFromDiagonal(a2[0], 0, a2[1], 1);
Rectangle2D r3 = r1.createIntersection(r2);
return new double[] { r3.getMinX(), r3.getMaxX() };
}