2019 Java Chapter 20 (Week 16)

From: 2019-09-04 00:00:00 To: 2019-12-31 00:00:00 Now: 2024-11-23 18:30:42 Status: Public

A - 2차평면의 점을 정렬하기

Time Limit: 1s Memory Limit: 128MB

Snippet Judge Submissions: 39 Solved: 16
Description

다음 요구사항을 만족하는 프로그램을 작성하라.

■ Point 클래스는 x좌표와 y좌표를 데이터를 가진다. Point 객체들을 좌표에 따라 오름차순으로 정렬하기 위해 Comparable 인터페이스를 정의하라. Point 개체들에 대해서 먼저 x좌표를 기준으로 정렬하고, 복수의 Point가 동일한 x좌표를 가진다면 y좌표로 정렬하라.

■ y좌표를 먼저 정렬하고, 그 다음 x좌표로 정렬하는 CompareY를 작성하라.

(Sort points in a plane) Write a program that meets the following requirements:

■ Define a class named Point with two data fields x and y to represent a point’s x- and y-coordinates. Implement the Comparable interface for comparing the points on x-coordinates. If two points have the same x-coordinates, compare their y-coordinates.

■ Define a class named CompareY that implements Comparator. Implement the comparemethod to compare two points on their y-coordinates. If two points have the same y-coordinates, compare their x-coordinates.

■ Randomly create 100 points and apply the Arrays.sort method to display the points in increasing order of their x-coordinates and in increasing order of their y-coordinates, respectively.

Input

* Line 1 : Point 개수 N (1~2,000 범위의 정수) 

* Line 2~N+1 : x y (x,y는 -1,000~1,000범위의 정수)

 

Output

X와 Y로 정렬된 점을 Sample Output과 같은 형식으로 출력

 

Sample Code
import java.util.Arrays;
import java.util.Scanner;
import java.util.Comparator;

public class Main {
    // Each row in points represents a point
    private double[][] points;

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        Point[] points = new Point[N];
        for (int i = 0; i < points.length; i++) {
            points[i] = new Point(sc.nextInt(), sc.nextInt());
        }

        System.out.println("Sort on x-coordinates");
        Arrays.sort(points);
        for (int i = 0; i < points.length; i++) {
            System.out.println(points[i]);
        }

        System.out.println("Sort on y-coordinates");
        Arrays.sort(points, new CompareY());
        for (int i = 0; i < points.length; i++) {
            System.out.println(points[i]);
        }
    }

    YOUR_CODE

}
Sample Input
5
1 3
-10 -9
0 3
-2 9
0 4
Sample Output
Sort on x-coordinates
(-10.0, -9.0)
(-2.0, 9.0)
(0.0, 3.0)
(0.0, 4.0)
(1.0, 3.0)
Sort on y-coordinates
(-10.0, -9.0)
(0.0, 3.0)
(1.0, 3.0)
(0.0, 4.0)
(-2.0, 9.0)
Hint
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
Source

JAVA2015 PE20.4