package chapter1_2;
import edu.princeton.cs.algs4.*;
public class exc2_3 {
public static void main(String[] args) {
System.out.println("输入2D间隔的数量:");
int N = StdIn.readInt();
System.out.println("输入间隔宽和高的最大值 max 和最小值 min");
double max = StdIn.readDouble();
double min = StdIn.readDouble();
/*
* 算法四 API 中对于绘图有这样的介绍:
* Canvas scale and coordinate system.</b>
* By default, all drawing takes places in the unit square, with (0, 0) at
* lower left and (1, 1) at upper right. You can change the default
* coordinate system with the following methods:
* 默认情况下,所有绘图都在一个单位正方形中进行其中(0,0)位于
* 左下和右上(1,1)。您可以采用以下方法更改坐标系默认值:
* setXscale(double xmin, double xmax)}
* setYscale(double ymin, double ymax)}
* setScale(double min, double max)}
* */
StdDraw.setScale(min,max);
double[] point1 = new double[N]; //min - max 之间的点
double[] point2 = new double[N]; //min - max 之间的点
Point2D[] point2D_lo = new Point2D[N]; //一维间隔左边的点
Point2D[] point2D_hi = new Point2D[N]; //一维间隔右边的点
Interval1D[] interval1D = new Interval1D[N]; //创建一维对象
Interval2D[] interval2D = new Interval2D[N]; //创建二维对象
//随机获取 min - max 之间的两个点
for (int i = 0; i < N; i++) {
point1[i] = StdRandom.uniform(min, max);
point2[i] = StdRandom.uniform(min, max);
//创建1 维间隔间隔,首先判断point1 与 point2 的大小
double lo_point, hi_point;
if (point1[i] < point2[i]) {
lo_point = point1[i];
hi_point = point2[i];
} else {
lo_point = point2[i];
hi_point = point1[i];
}
//将一维间隔的左右点分别存入 point2D_lo, point2D_hi
point2D_lo[i] = new Point2D(lo_point,lo_point);
point2D_hi[i] = new Point2D(hi_point,hi_point);
//Interval1D 与 Interval2D 不能分开,例如不能将 Interval1D 放入if 语句而 Interval2D 在if 语句外
interval1D[i] = new Interval1D(lo_point, hi_point);
//创建一个2 维间隔,绘图
interval2D[i] = new Interval2D(interval1D[i], interval1D[i]);
interval2D[i].draw();
}
//打印出有相交间隔对的数量
int intersect_num = 0;
int contains_num = 0;
for (int i = 0; i < N-1; i++) {
for (int j = i+1; j < N; j++) {
if(interval2D[i].intersects(interval2D[j])){
intersect_num++;
}
//如果二维间隔既包括左边的点point2D_lo,又包括右边的点point2D_hi
if(interval2D[i].contains(point2D_lo[j])&&interval2D[i].contains(point2D_hi[j])){
contains_num++;
}else if(interval2D[j].contains(point2D_lo[i])&&interval2D[j].contains(point2D_hi[i])){
contains_num++;
}
}
}
System.out.println("相交间隔对的数量:" + intersect_num);
System.out.println("有包含关系的间隔对数量:" + contains_num);
}
}
《算法》第四版练习 1.2.3
最新推荐文章于 2021-04-26 08:55:38 发布