Post

Class_좌표 정렬

✅ N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램을 작성하세요. 정렬기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;

 class Point implements Comparable<Point>{
    public int x;
    public int y;

    public Point(int x, int y){
        this.x= x;
        this.y=y;
    }

     @Override
     public int compareTo(Point o) {
         if(this.x == o.x) return this.y-o.y; //x가 같으면 y에 의해서 비교해라
         else return this.x- o.x; //x에 의해서 비교해라
     }
 }
class Main {
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n= sc.nextInt();
        ArrayList<Point> coordiate= new ArrayList<>();
        for(int i=0; i<n; i++){
            int x= sc.nextInt();
            int y= sc.nextInt();
            coordiate.add(new Point(x, y));
        }
        Collections.sort(coordiate);
        for(Point p: coordiate){
            System.out.println(p.x+ " "+ p.y);
        }

    }
}
//⭐️input:
5
2 7
1 3
1 2
2 5
3 6
//⭐️output:
1 2
1 3
2 5
2 7
3 6

🔵 ThingsILearned

✔️ 좌표 클라스

  1. Point라는 클래스
  2. int x, int y는 모두 public(Main 클래스에서도 쓰여야 하니까)
  3. 생성자 만들기

✔️ 비교하는 클래스 implements Comparable

  1. 비교 위해 implements Comparable
  2. implements Comparable@Override CompareTo
  3. 그리고 @Override CompareTo는 항상 음수를 return해야 한다.
    —– 여기서부터 나만의 정렬기준 만들기 —–
  4. 우리는 오름차순으로 정렬하고 싶으니까
  5. 지금 객체this.x가 비교하는 객체o.x보다 작아야 함
  6. 따라서 음수를 return하기 위해서는 지금 객체this.x - 비교하는 객체o.x
  7. 만약 x값이 같다면, y값으로 비교

코딩공책-45

✔️ ArrayList 정렬하기 Collections.sort

이 코드가 없으면 정렬이 되지 않음
코드를 추가해서 정렬 필수!

This post is licensed under CC BY 4.0 by the author.