1.2.3 Write an Interval2D client that takes command-line arguments N, min, and max and generates N random 2D intervals whose width and height are uniformly distributed between min and max in the unit square. Draw them on StdDraw and print the number of pairs of intervals that intersect and the number of intervals that are contained in one another
import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.Interval2D;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;
public class E123 {
//对随机生成的min和max排序
public static double[] interval(double min,double max) {
double[] boundary = new double[2];
if (min < max)
{
boundary[0] = min;
boundary[1] = max;
}
else
{
boundary[0] = max;
boundary[1] = min;
}
return boundary;
}
public static void main(String[] args) {
final int N = Integer.parseInt(args[0]);
final double min = Double.parseDouble(args[1]);
final double max = Double.parseDouble(args[2]);
StdDraw.setXscale(0.0,1.0);
StdDraw.setYscale(0.0,1.0);
Interval2D[] boxes = new Interval2D[N];
//保存一个box的左下角坐标和由上角坐标,通过对角点判断两个两个box是否存在包含关系
Point2D[] leftbottom = new Point2D[N];
Point2D[] righttop = new Point2D[N];
for (int i = 0;i < N;i++)
{
double xMin = StdRandom.uniform(min, max);
double xMax = StdRandom.uniform(min, max);
double yMin = StdRandom.uniform(min, max);
double yMax = StdRandom.uniform(min, max);
double[] xInterval = interval(xMin, xMax);
double[] yInterval = interval(yMin, yMax);
leftbottom[i] = new Point2D(xInterval[0],yInterval[0]);
righttop[i] = new Point2D(xInterval[1], yInterval[1]);
Interval1D interval1dx = new Interval1D(xInterval[0], xInterval[1]);
Interval1D interval1dy = new Interval1D(yInterval[0], yInterval[1]);
boxes[i] = new Interval2D(interval1dx, interval1dy);
boxes[i].draw();
}
int count1 = 0; //记录相交的间隔对的数量
int count2 = 0; //记录有包含关系的间隔对数量
for (int i = 0;i < N;i++)
{
for (int j = i + 1; j < N;j++)
{
if (boxes[i].intersects(boxes[j])) count1++;
if ((boxes[i].contains(leftbottom[j]) && boxes[i].contains(righttop[j])) || (boxes[j].contains(leftbottom[i]) && boxes[j].contains(righttop[i]))) count2++;
}
}
System.out.printf("具有相交关系的间隔对的数量为%d\n", count1);
System.out.printf("具有包含关系的间隔对的数量为%d\n", count2);
}
}
测试结果