Sorting: Comparator

HeeSeong·2021년 6월 28일
0

HackerRank

목록 보기
11/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/ctci-comparator-sorting/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting


❔ 문제 설명


Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields:

  • name : a string.
  • score : an integer.

Given an array of Player objects, write a comparator that sorts them in order of decreasing score. If 2 or more players have the same score, sort those players alphabetically ascending by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. In short, when sorting in ascending order, a comparator function returns -1 if a < b, 0 if a = b, and 1 if a > b.

Declare a Checker class that implements the comparator method as described. It should sort first descending by score, then ascending by name. The code stub reads the input, creates a list of Player objects, uses your method to sort the data, and prints it out properly.

Example

n = 3
data = [[smith, 20],[jones,15],[jones,20]]

Sort the list as data = [[jones,20],[smith, 20],[jones,15]]. Sort first descending by score, then ascending by name.

Input Format

The first line contains an integer, n, the number of players.
Each of the next n lines contains a player's name and score, a string and an integer.

Output Format

You are not responsible for printing any output to stdout. Locked stub code in Solution will instantiate a Checker object, use it to sort the Player array, and print each sorted element.


⚠️ 제한사항


  • 0score10000 ≤ score ≤ 1000

  • Two or more players can have the same name.

  • Player names consist of lowercase English alphabetic letters.



💡 풀이 (언어 : Java)


객체를 사용자가 정의한 정렬 기준에 맞춰 정렬해야 하는 경우에 사용하는 인터페이스로 Comparable와 Comparator가 있다고 한다. Comparable은 정렬 수행 시 기본적으로 적용되는 정렬 기준이 되는 메서드를 정의하는 인터페이스고, Comparator는 기본 정렬 기준과 다르게 정렬 하고 싶을 때 사용하는 인터페이스이다. 이번에 문제를 풀기위해 간단하게 보았는데, 다음에 다시 볼때는 자세히 보고싶다.

import java.util.*;

class Player {
	String name;
	int score;

	Player(String name, int score) {
		this.name = name;
		this.score = score;
	}
}

class Checker implements Comparator<Player> {

    @Override
    public int compare(Player o1, Player o2) {
        if (o1.score > o2.score) {
            return -1;
        } else if (o1.score < o2.score) {
            return 1;
        } else {
            return o1.name.compareTo(o2.name);
        }
    }
    
}



public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();
        
        for(int i = 0; i < n; i++){
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();

        Arrays.sort(player, checker);
        for(int i = 0; i < player.length; i++){
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글