编写Interval2D用例
  1. import edu.princeton.cs.algs4.Interval1D;
  2. import edu.princeton.cs.algs4.Interval2D;
  3. import edu.princeton.cs.algs4.Point2D;
  4. import edu.princeton.cs.algs4.StdOut;
  5. public class Ex1_2_3 {
  6. private static void draw2D(int N,double min,double max) {
  7. Interval2D[] box = new Interval2D[N];
  8. Point2D[][] point = new Point2D[N][4];
  9. double xlo,xhi,ylo,yhi;
  10. int intersectCount = 0, containCount = 0;
  11. for(int i=0; i<N; i++) {
  12. do xlo = Math.random();
  13. while (xlo < min || xlo > max);
  14. do xhi = Math.random();
  15. while (xhi < min || xhi > max || xhi < xlo );
  16. do ylo = Math.random();
  17. while (ylo < min || ylo > max);
  18. do yhi = Math.random();
  19. while (yhi < min || yhi > max || yhi < ylo );
  20. Interval1D xinterval = new Interval1D(xlo,xhi);
  21. Interval1D yinterval = new Interval1D(ylo,yhi);
  22. box[i] = new Interval2D(xinterval,yinterval);
  23. point[i][0] = new Point2D(xlo,ylo);
  24. point[i][1] = new Point2D(xlo,yhi);
  25. point[i][2] = new Point2D(xhi,ylo);
  26. point[i][3] = new Point2D(xhi,yhi);
  27. box[i].draw();
  28. }//绘图循环
  29. for(int i=0; i<N; i++) {
  30. for(int j=i+1; j<N; j++) {
  31. if(box[i].intersects(box[j])) {
  32. intersectCount++;
  33. }
  34. }
  35. }//遍历判断相交
  36. StdOut.println(intersectCount);
  37. for(int i=0; i<N; i++) {
  38. for(int j=0; j<N; j++) {
  39. if(box[i].contains(point[j][0])
  40. &&box[i].contains(point[j][1])
  41. &&box[i].contains(point[j][2])
  42. &&box[i].contains(point[j][3])) {
  43. containCount++;
  44. }
  45. }
  46. }//遍历判断包含
  47. containCount -= N;
  48. StdOut.println(containCount);
  49. }
  50. public static void main(String[] args) {
  51. int N = Integer.parseInt(args[0]);
  52. double min = Double.parseDouble(args[1]);
  53. double max = Double.parseDouble(args[2]);
  54. draw2D(N,min,max);
  55. }
  56. }

要点:

判断矩形间相交用组合思想,N_(N-1)次循环,不重复计算相交;判断矩形间包含时用排列思想,N_N次循环,才能判断包含.