- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
Latest commit
50 lines (41 loc) · 1.4 KB
/
Copy pathsolution.java
File metadata and controls
50 lines (41 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
importjava.util.*;
classCheckerimplementsComparator<Player> {
@Override
publicintcompare(Playerp1, Playerp2) {
if(p1.score == p2.score) {
returnp1.name.compareTo(p2.name);
} else {
returnp2.score - p1.score;
}
}
}
classPlayer{
Stringname;
intscore;
Player(Stringname, intscore){
this.name = name;
this.score = score;
}
}
classSolution {
publicstaticvoidmain(String[] args) {
Scannerscan = newScanner(System.in);
intn = scan.nextInt();
Player[] player = newPlayer[n];
Checkerchecker = newChecker();
for(inti = 0; i < n; i++){
player[i] = newPlayer(scan.next(), scan.nextInt());
}
scan.close();
Arrays.sort(player, checker);
for(inti = 0; i < player.length; i++){
System.out.printf("%s %s\n", player[i].name, player[i].score);
}
}
}
/* EXPLANATION: Reference: https://www.hackerrank.com/challenges/java-comparator/forum/comments/260536
Returning p2.score - p1.score sorts the Players in descending order according to their scores.
The exact value that the compare function returns is not important.
It just has to return 0 if scores are equal, a negative number if p1 should be placed before p2 when sorting,
and a positive number if p2 should be placed before p1 when sorting.
*/