feat: Comparator
This commit is contained in:
parent
c020c11f0c
commit
9bf93b9d7e
2 changed files with 91 additions and 0 deletions
|
@ -0,0 +1,52 @@
|
|||
package eu.ztsh.training.hackerrank.datastructures.comparator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* source: <a href="https://www.hackerrank.com/challenges/java-comparator">Java Comparator</a>
|
||||
*/
|
||||
|
||||
class Checker implements Comparator<Player> {
|
||||
|
||||
@Override
|
||||
public int compare(Player o1, Player o2) {
|
||||
var points = o2.score - o1.score;
|
||||
return points != 0 ? points : o1.name.compareTo(o2.name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Hackerrank code below (slightly modified)
|
||||
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);
|
||||
Arrays.stream(player).forEach(value -> System.out.printf("%s %s%s", value.name, value.score, System.lineSeparator()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class Player {
|
||||
|
||||
String name;
|
||||
int score;
|
||||
|
||||
Player(String name, int score) {
|
||||
this.name = name;
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package eu.ztsh.training.hackerrank.datastructures.comparator;
|
||||
|
||||
import eu.ztsh.training.hackerrank.HackerRankTest;
|
||||
import eu.ztsh.training.hackerrank.SolutionClassDescription;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@DisplayName("HackerRank challenges: Java Comparator")
|
||||
class SolutionTest extends HackerRankTest {
|
||||
|
||||
@Test
|
||||
public void testCase0() {
|
||||
simpleAssert(
|
||||
List.of(
|
||||
"5",
|
||||
"amy 100",
|
||||
"david 100",
|
||||
"heraldo 50",
|
||||
"aakansha 75",
|
||||
"aleksa 150"
|
||||
),
|
||||
List.of(
|
||||
"aleksa 150",
|
||||
"amy 100",
|
||||
"david 100",
|
||||
"aakansha 75",
|
||||
"heraldo 50"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SolutionClassDescription getSolutionClassDescription() {
|
||||
return new SolutionClassDescription(Solution.class);
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue