We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Sorting: Comparator
  2. Discussions

Sorting: Comparator

Problem
Submissions
Leaderboard
Discussions
Editorial
Topics

Sort 450 Discussions, By:

votes

Please Login in order to post a comment

  • kreznykov
    6 years ago+ 8 comments

    It should have a super easy difficulty.

    138|
    Permalink
    View more Comments..
  • gussy
    6 years ago+ 8 comments

    In Python 3, I think the template code is incorrect. We can solve it by writing this

        def comparator(a, b):
            if a.score < b.score:
                return 1
            if a.score > b.score:
                return -1
            if a.name < b.name:
                return -1
            if a.name > b.name:
                return 1
            return 0
    

    However if the line

    data = sorted(data, key=cmp_to_key(Player.comparator))
    

    was changed to

    data = sorted(data, key=Player.key)
    

    we could solve it with the better

        def key(self):
            return(-self.score, self.name)
    

    We can use the second approach by dummying out the cmp_to_key function.

    def cmp_to_key(key):
        return key
    
    class Player:
        def __init__(self, name, score):
            self.name = name
            self.score = score
            
        def comparator(self):
            return(-self.score, self.name)
    
    66|
    Permalink
    View more Comments..
  • jimmyxbw
    5 years ago+ 1 comment

    Simple Java implementation:

    class Checker implements Comparator<Player> {
        @Override
        public int compare(Player a, Player b) {
            if(a.score != b.score) {
                return b.score - a.score;
            }
            return a.name.compareTo(b.name);
        }
    }
    
    40|
    Permalink
  • solidwater
    5 years ago+ 3 comments

    Hi Team,

    Can you also enable C# in editor for this problem

    32|
    Permalink
  • samirbaaz
    5 years ago+ 3 comments
    class Player:
        def __init__(self, name, score):
            self.name = name
            self.score = score
        def __repr__(self):
            pass
        def comparator(a, b):
            val = b.score - a.score
            if val == 0:
                return -1 if a.name < b.name else 1
            return val
    
    24|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature