编写Interval2D用例
import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.Interval2D;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdOut;
public class Ex1_2_3 {
private static void draw2D(int N,double min,double max) {
Interval2D[] box = new Interval2D[N];
Point2D[][] point = new Point2D[N][4];
double xlo,xhi,ylo,yhi;
int intersectCount = 0, containCount = 0;
for(int i=0; i<N; i++) {
do xlo = Math.random();
while (xlo < min || xlo > max);
do xhi = Math.random();
while (xhi < min || xhi > max || xhi < xlo );
do ylo = Math.random();
while (ylo < min || ylo > max);
do yhi = Math.random();
while (yhi < min || yhi > max || yhi < ylo );
Interval1D xinterval = new Interval1D(xlo,xhi);
Interval1D yinterval = new Interval1D(ylo,yhi);
box[i] = new Interval2D(xinterval,yinterval);
point[i][0] = new Point2D(xlo,ylo);
point[i][1] = new Point2D(xlo,yhi);
point[i][2] = new Point2D(xhi,ylo);
point[i][3] = new Point2D(xhi,yhi);
box[i].draw();
}//绘图循环
for(int i=0; i<N; i++) {
for(int j=i+1; j<N; j++) {
if(box[i].intersects(box[j])) {
intersectCount++;
}
}
}//遍历判断相交
StdOut.println(intersectCount);
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
if(box[i].contains(point[j][0])
&&box[i].contains(point[j][1])
&&box[i].contains(point[j][2])
&&box[i].contains(point[j][3])) {
containCount++;
}
}
}//遍历判断包含
containCount -= N;
StdOut.println(containCount);
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double min = Double.parseDouble(args[1]);
double max = Double.parseDouble(args[2]);
draw2D(N,min,max);
}
}
要点:
判断矩形间相交用组合思想,N_(N-1)次循环,不重复计算相交;判断矩形间包含时用排列思想,N_N次循环,才能判断包含.