Sorting: Comparator

Sort by

recency

|

508 Discussions

|

  • + 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);
         }
        }
    
  • + 1 comment

    I do think that the prompt is very confunsing, it says a checker is being called, but you have to implement the checker yourself, and that the Comparator interface exists? It was really confusing.

    • + 0 comments

      i think the same