Sorting: Comparator

Sort by

recency

|

509 Discussions

|

  • + 0 comments

    The Player class is provided in the editor below.

    Uh, no it isn't. There's no Player class already in the code, regardless of the programming language. Does it expect us to write this class ourselves? I'm confused. How do I solve this question when there's clearly something missing that's needed to solve it?

  • + 0 comments

    Python

    def comparator(a, b):
        # First, sort by descending score.
        if a.score > b.score:
            return -1
        elif a.score < b.score:
            return 1
        else:
            # If scores are equal, sort by ascending name.
            if a.name < b.name:
                return -1
            elif a.name > b.name:
                return 1
            else:
                return 0
    
  • + 0 comments

    Write this stupid question in pyton is so confusing. "You must use a Checker class" but lock the code preventing you to use any other class beside Player. Someone need to edit the narrative of this problem.

  • + 0 comments

    C#

    class Solution {

    struct Player{
        public string name {get; set;}
        public int score {get; set;}
    
        public Player(string playerName, int playerScore){
            name = playerName;
            score = playerScore;
        }
    }
    
    class Checker : IComparer<Player>{
        public int Compare(Player a, Player b){
            if(b.score != a.score)
                return b.score.CompareTo(a.score);
            return a.name.CompareTo(b.name);
        }
    }
    
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
    
        int n = Convert.ToInt32(Console.ReadLine());
        var players = new Player[n];
    
        for (int i = 0; i < n; i++)
        {
            string[] input = Console.ReadLine().Split();
            players[i] = ( new Player { name = input[0], score = Convert.ToInt32(input[1])});
        }
    
        //var list = players.OrderByDescending(p => p.score).ThenBy(p => p.name);
        Array.Sort(players, new Checker());
        foreach(var player in players)
        {
            Console.WriteLine($"{player.name} {player.score}");
        }
        Console.ReadLine();
    }
    

    }

  • + 0 comments

    Java #

    public int compare(Player a, Player b) {
           
        int ageComarator = Integer.valueOf(b.score).compareTo(a.score);
         if (ageComarator != 0) {
            return ageComarator;
         } else {
           return a.name.compareTo(b.name);
         }
        }