A) 了解情况:
根据 1D 区间定义 2D 区间 A 和 B:
A = Ixa x Iya = [x1a, x2a] x [y1a, y2a]
B = Ixb x Iyb = [x1b, x2b] x [y1b, y2b]
然后
A is contained in B, iff
Ixa = [x1a, x2a] is contained in Ixb [x1b, x2b] and
Iya = [y1a, y2a] is contained in Iyb = [y1b, y2b].
使用
I1 = [a, b] is contained in I2 = [c, d] iff c <= a and b <= d.
这类似于 Interval2D ( http://algs4.cs.princeton.edu/12oop/Interval2D.java.html ) 和 Intervall1D ( http://algs4.cs.princeton.edu/12oop/中的 intersect 方法的实现。 Interval1D.java.html ) 只是他们测试条件的逻辑逆。
B)现在你的方法:
如果您检查左下角 (x1a, y1a) 和右上角 (x2a, y2a) 点, contains(Point2D) 应该允许进行测试:
A is contained in B, iff B contains (x1a, y1a) and B contains (x2a, y2a).
丑陋的是,虽然 Interval1D 有获取器来访问私有的左右坐标,但 Interval2D 没有访问它的私有 x 和 y(一维)间隔。您可以从其 toString() 输出中解析它们,但这很丑陋且工作量太大。创建一些超类
public class Rect {
public Interval1D x;
public Interval1D y;
public Interval2D r;
Rect(Interval1D px, Interval1D py) {
x = px;
y = py;
r = new Interval2D(px, py);
}
public boolean contains(Rect that) {
if (!this.r.contains(new Point2D(that.x.left(), that.y.left()))) return false;
if (!this.r.contains(new Point2D(that.x.right(), that.y.right()))) return false;
return true;
}
}
并且使用它只是丑陋的。