Leaderboard
# Topic
Comparable
# Problem
Leaderboard
There is an application to create leaderboards of e-sports competitions. It uses the Score
class to represent a score of each player. This class has two fields: player
for the player's name and totalScore
for that player's total score. To build a leaderboard, the Score
objects need to be compared. A Score
object is considered bigger than another Score
if it's totalScore
value is bigger. If totalScore
values of two Score
objects are the same, such objects must be compared by their player
values. See the example below.
# Code of problem
import java.util.*;
class Score implements Comparable<Score> {
private final String player;
private final int totalScore;
public Score(String player, int totalScore) {
this.player = player;
this.totalScore = totalScore;
}
public String getPlayer() {
return player;
}
public int getTotalScore() {
return totalScore;
}
@Override
public String toString() {
return player + '=' + totalScore;
}
@Override
public int compareTo(Score score) {
// your code here
}
}
// do not change the code below
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Score> scores = new ArrayList<>();
while (sc.hasNextLine()) {
String[] input = sc.nextLine().split(" ");
Score score = new Score(input[0], Integer.parseInt(input[1]));
scores.add(score);
}
Collections.sort(scores);
System.out.println(scores);
}
}
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
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
# Hint & Explain
compare both fields (score then player)
# Solution
# My solution
// your code here
if (getTotalScore() > score.getTotalScore()) return 1;
else if (getTotalScore() < score.getTotalScore()) return -1;
else {
return getPlayer().compareTo(score.getPlayer());
}
1
2
3
4
5
6
2
3
4
5
6
BAD!
# Other solution 1
// your code here
int result = Integer.compare(totalScore, score.totalScore);
return result == 0 ? player.compareTo(score.player) : result;
1
2
3
2
3
# Other solution 2
// your code here
if (totalScore == score.totalScore) {
return player.compareTo(score.player);
} else {
return Integer.compare(totalScore, score.totalScore);
}
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2022/10/12, 17:01:25