算法第四版 1.2.2
题目:
编写一个Interval2D的用例,从命令行接收参数n,min,max的输入;生成n个随机的2D间隔,
其宽和高均匀的分布在单位正方形中的min,和max之间。用StdDraw画出它们,并打印出相交的间隔数量;
ac代码如下:(注意我没有用命令行输入,我用的是eclipse输入)
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.StdIn; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; public class No_1_2_3 { public static void main(String[] args) { int n = StdIn.readInt(); Interval2D[] a = new Interval2D[n]; double min = 0.0; double max = 1.0; for(int i =0;i<n;i++) { double xlo = StdRandom.uniform(min, max);//生成min到max之间的实数xlo double xhi = StdRandom.uniform(min, max); if(xlo>xhi) { double temp; temp = xlo; xlo = xhi; xhi = temp; } double ylo = StdRandom.uniform(min, max); double yhi = StdRandom.uniform(min, max); if(ylo>yhi) { double temp; temp = ylo; ylo = yhi; yhi= temp; } Interval1D x = new Interval1D(xlo,xhi);//先生成直线间隔x和y Interval1D y = new Interval1D(ylo,yhi); a[i] = new Interval2D(x,y);//再用x,y创建二维的对象 a[i].draw(); } StdDraw.setPenColor(StdDraw.RED); StdDraw.setPenRadius(0.005); Interval1D x0 = new Interval1D(min,max); Interval1D y0 = new Interval1D(min,max); new Interval2D(x0,y0).draw(); int count1=0,count2 = 0; for(int i=0;i<n;i++)//计算有多少有交集的二维对象 { for(int j=i+1;j<n;j++) { if(a[i].intersects(a[j])) count1++; } } StdOut.println(count1); } }