1.2.1
package chapter1;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdRandom;
public class prac1_2_Point2D {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
StdDraw.setCanvasSize(800, 800);
StdDraw.setXscale(0, 50);
StdDraw.setYscale(0, 50);
StdDraw.setPenRadius(.005);
Point2D[] points = new Point2D[N];
for (int i = 0; i < N; i++) {
int x = StdRandom.uniform(50);
int y = StdRandom.uniform(50);
points[i] = new Point2D(x, y);
points[i].draw();
}
double min = Double.POSITIVE_INFINITY;
int p1 = 0, p2 = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
double dis = points[i].distanceTo(points[j]);
if (dis < min) {
min = dis;
p1 = i;
p2 = j;
}
}
}
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.line(points[p1].x(), points[p1].y(), points[p2].x(), points[p2].y());
}
}
1.2.2
package chapter1;
import edu.princeton.cs.algs4.Interval1D;
public class prac1_2_Interval1D {
public static void main(String[] args) {
Interval1D[] intervals = new Interval1D[4];
intervals[0] = new Interval1D(15.0, 33.0);
intervals[1] = new Interval1D(45.0, 60.0);
intervals[2] = new Interval1D(20.0, 70.0);
intervals[3] = new Interval1D(46.0, 55.0);
for (int i = 0; i < intervals.length; i++) {
for (int j = i + 1; j < intervals.length; j++) {
if (intervals[i].intersects(intervals[j]) == true) {
System.out.printf("%.1f %.1f, %.1f %.1f\n", intervals[i].min(), intervals[i].max(),
intervals[j].min(), intervals[j].max());
}
}
}
}
}