점은 점의 좌표 인 두 개의 인스턴스 변수가있는 클래스입니다. (x, y) Point는 Comparable 인터페이스를 구현합니다. 그러나 좌표로 비교하는 것 외에도 다른 점 (x0, y0)에 대한 상대 기울기 인 (x1, y1)과 (x2, y2)를 비교할 수 있습니다. 다음은 Point 클래스입니다.Arrays.sort (pointsBySlope, p.SLOPE_ORDER)는 pointsBySlope []가 무엇인지에 따라 달라 집니까?
import java.util.Comparator;
public class Point implements Comparable<Point> {
// compare points by slope
public final Comparator<Point> SLOPE_ORDER = new Ordering();
private final int x; // x coordinate
private final int y; // y coordinate
// create the point (x, y)
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
private class Ordering implements Comparator<Point>{
@Override
public int compare(Point p1, Point p2) {
if(slopeTo(p1) - slopeTo(p2) < 0) return -1;
else if(slopeTo(p1) - slopeTo(p2) > 0) return 1;
else return 0;
}
}
// slope between this point and that point
public double slopeTo(Point that) {
/* YOUR CODE HERE */
if(this.y == that.y && this.x == that.x) return Double.NEGATIVE_INFINITY;
else if(this.y == that.y) return 0;
else if(this.x == that.x) return Double.POSITIVE_INFINITY;
else return ((double)that.y - (double)this.y)/((double)that.x - (double)this.x);
}
// is this point lexicographically smaller than that one?
// comparing y-coordinates and breaking ties by x-coordinates
public int compareTo(Point that) {
/* YOUR CODE HERE */
if(this.y < that.y){
return -1;
}else if(this.y > that.y){
return 1;
}else{
if(this.x < that.x) return -1;
else if(this.x > that.x) return 1;
else return 0;
}
}
}
이제 경사로 정렬이 작동하는지 테스트하는 간단한 테스트 클래스를 작성했습니다.
public class Test {
public static void main(String[] args) {
In in = new In(args[0]);
int N = in.readInt();
Point[] points = new Point[N];
Point[] pointsBySlope = new Point[N];
for (int i = 0; i < N; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
pointsBySlope[i] = points[i];
}
Arrays.sort(points);
Arrays.sort(pointsBySlope);
Point p = points[2];
Arrays.sort(pointsBySlope, p.SLOPE_ORDER);
p = points[3];
Arrays.sort(pointsBySlope, p.SLOPE_ORDER);
for(int i=0;i<pointsBySlope.length;i++){
System.out.println(pointsBySlope[i].toString()+" , ");
}
System.out.println("\n\n"+"=================================");
Arrays.sort(pointsBySlope);
Arrays.sort(pointsBySlope, p.SLOPE_ORDER);
for(int i=0;i<pointsBySlope.length;i++){
System.out.println(pointsBySlope[i].toString()+" , ");
}
}
}
출력은
(19000, 10000) ,
(18000, 10000) ,
(14000, 10000) ,
(21000, 10000) ,
(32000, 10000) ,
(1234, 5678) ,
(19000, 10000) ,
(14000, 10000) ,
(18000, 10000) ,
(21000, 10000) ,
(32000, 10000) ,
(1234, 5678) ,
왜 서로 다른 두 경우 모두에서 출력입니까? 처음에 SLOPE_ORDER로 정렬 할 때 자연스러운 순서로 pointsBySlope 배열을 정렬 한 다음 SLOPE_ORDER로 정렬하면 어떻게 다른 출력이 생성됩니까?
디버거로 무엇을 배우면서 무엇을 배웠습니까? –