Header Ad

HackerRank Sorting: Comparator Interview preparation kit problem solution

In this HackerRank Sorting: Comparator Interview preparation kit you have Given an array of n 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. 


HackerRank Sorting: Comparator Interview preparation kit solution


Problem solution in Python programming.

from functools import cmp_to_key
class Player:
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def __repr__(self):
        self.name = ""
        self.score = 0
    def comparator(a, b):
        if a.score == b.score:
            if a.name > b.name:
                return 1
            else:
                return -1
        if a.score > b.score:
            return -1
        else:
            return 1
        
        

n = int(input())
data = []
for i in range(n):
    name, score = input().split()
    score = int(score)
    player = Player(name, score)
    data.append(player)
    
data = sorted(data, key=cmp_to_key(Player.comparator))
for i in data:
    print(i.name, i.score)



Problem solution in Java Programming.

import java.util.*;

class Player {
    String name;
    int score;

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

// Write your Checker class here
class Checker implements Comparator<Player> {
    
    @Override
    public int compare(Player p1, Player p2) {
        if (p1.score == p2.score) {
            return p1.name.compareTo(p2.name);
        }
        return -Integer.compare(p1.score, p2.score);
    }
    
}


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);
        }
    }
}


Problem solution in C++ programming.

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

struct Player {
  string name;
  int score;
};

int main() {
  int n; cin >> n;
  vector<Player> players(n);
  for(int i = 0; i < n; cin >> players[i].name, cin >> players[i].score, ++i);
  sort(players.begin(), players.end(), [](Player &a, Player &b) {
    if(a.score > b.score) return true;
    if(a.score == b.score) return a.name < b.name;
    return false;
  });
  for(const auto &player : players) cout << player.name << " " << player.score << endl;
}


Post a Comment

0 Comments