The code is a solution to a problem where we have a list of players, each with a name and a score. The task is to sort the players first by their score in descending order, and then by their name in alphabetical order if the scores are equal.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution creates a 'Player' class to hold the name and score of each player, and a 'Checker' class that implements the Comparator interface to define the sorting rules. In the 'compare' method of the 'Checker' class, it first checks if the scores of two players are equal. If they are, it compares their names alphabetically. If they are not, it compares their scores in descending order. The 'main' method reads the players' data, sorts the players array using the 'Arrays.sort' method with the 'checker' as the sorting rule, and then prints out the sorted players.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
/**
*
*/
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 {
public int compare(Player o1, Player o2) {
if (o1.score == o2.score) {
return ((o1.name).compareTo(o2.name));
} else {
return ((o2.score - o1.score));
}
}
}
public class JavaComparator {
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);
}
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.