ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [코드트리 조별과제] 객체
    Algorithm 2024. 8. 4. 21:21


    코딩테스트에 감이 떨어지기도 하고, 코테를 꾸준하게 도전하기 위해 코드트리 조별과제에 참여하게 되었다.

    내가 스스로 공부한 것을 조별과제에 참여할 겸, 기록에 남기기위해 정리하려고한다. 

     

     

    객체 정렬하기


    public class Main {
        public static class Student {
            String id;
            int score;
    
            public Student(String id, int score) {
                this.id = id;
                this.score = score;
            }
        }
     }

     

    위에와 같이 Student라는 객체가 있고, Score를 기준으로 정렬을 하기 위해선 Comparable 인터페이스가 필요하다.

     

    Comparable 인터페이스란, 


    Comparable 인터페이스의 compareTo() 메소드를 통해 대소 비교가 가능하다.

    메소드를 호출하는 객체가 파라미터 객체보다 작을 경우 음수를 리턴하고, 크기가 동일하다면 0, 클 경우엔 양수를 리턴해준다. 

    즉, score를 기준으로 높은 점수 순으로 내림 차순 정렬을 원할 경우, 파라미터의 점수 - 자신 객체 점수

    작은 점수순으로 오름 차순 정렬을 원할 경우 자신 객체 점수 - 파라미터의 점수로 리턴 값을 지정해주면 된다. 

     

    아래 소스 코드로 설명해보겠습니다.

    먼저, comparable 인터페이스를 구현하도록 변경해줍니다. 이를 적용해보면 Student 클래스는 다음과 같이 수정됩니다.

    public class Main {
        public static class Student implements Comparable<Student> {
            String id;
            int score;
    
            public Student(String id, int score) {
                this.id = id;
                this.score = score;
            }
    
            public int getScore() {
                return this.score;
            }
    
            @Override
            public int compareTo(Student o1) {
                return o1.getScore() - this.score; // 점수 오름차순
            }
    
            @Override 
            public String toString() {
                StringBuffer sb = new StringBuffer();
                sb.append(this.id).append(" ").append(this.score);
    
                return sb.toString();
            }
        }

     

    public class Main {
        public static class Student implements Comparable<Student> {
            String id;
            int score;
    
            public Student(String id, int score) {
                this.id = id;
                this.score = score;
            }
    
            public int getScore() {
                return this.score;
            }
    
            @Override
            public int compareTo(Student o1) {
                return this.score - o1.getScore(); // 점수 내림차순
            }
    
            @Override 
            public String toString() {
                StringBuffer sb = new StringBuffer();
                sb.append(this.id).append(" ").append(this.score);
    
                return sb.toString();
            }
        }

     

     

    문제


    위에 개념과 관련하여 코드트리 문제 1문제를 같이 풀어보자

     

     

     

     

    입력을 받은 후, 오름차순으로 정렬을 한 후, 0번째를 출력하는 식으로 알고리즘을 구현했다.

     아래는 내가 짠 코드이다.

    import java.io.*;
    import java.util.*;
    
    public class Main {
        public static class Student implements Comparable<Student> {
            String id;
            int score;
    
            public Student(String id, int score) {
                this.id = id;
                this.score = score;
            }
    
            public int getScore() {
                return this.score;
            }
    
            @Override
            public int compareTo(Student o1) {
                return this.score - o1.getScore();
            }
    
            @Override 
            public String toString() {
                StringBuffer sb = new StringBuffer();
                sb.append(this.id).append(" ").append(this.score);
    
                return sb.toString();
            }
        }
    
        public static void main(String[] args) throws Exception {
            // 여기에 코드를 작성해주세요.
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            List<Student> studentList = new ArrayList();
    
            for (int i = 0; i < 5; i++) {
                String[] input = br.readLine().split(" ");
                Student student = new Student(input[0], Integer.parseInt(input[1]));
                studentList.add(student);
            }
    
            Collections.sort(studentList);
    
            System.out.println(studentList.get(0).toString());
        }
    }

     

    댓글

Designed by Tistory.