Skip to content

Commit be11e08

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank] Interview Preparation Kit: Sorting: Comparator. Solved ✅.
1 parent 93d2d3d commit be11e08

File tree

4 files changed

+288
-0
lines changed

4 files changed

+288
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# [Sorting: Comparator](https://www.hackerrank.com/challenges/ctci-comparator-sorting)
2+
3+
Write a Comparator for sorting elements in an array.
4+
5+
- Difficulty: `#medium`
6+
- Category: `#ProblemSolvingBasic` `#sorting`
7+
8+
Comparators are used to compare two objects.
9+
In this challenge, you'll create a comparator and use it to sort an array.
10+
The Player class is provided in the editor below. It has two fields:
11+
12+
1. `name`: a string.
13+
2. `score`: an integer.
14+
15+
Given an array of `n` Player objects,
16+
write a comparator that sorts them in order of decreasing score.
17+
18+
If `2` or more players have the same score,
19+
sort those players alphabetically ascending by name.
20+
To do this, you must create a Checker class that
21+
implements the Comparator interface,
22+
then write an int compare(Player a, Player b) method implementing the
23+
[Comparator.compare(T o1, T o2)](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T,%20T))
24+
method.
25+
In short, when sorting in ascending order,
26+
a comparator function returns `-1` if `a < b`,
27+
`0` if `a = b`, and `1` if `a > b`.
28+
29+
Declare a Checker class that implements the comparator method as described.
30+
31+
It should sort first descending by score,
32+
then ascending by name.
33+
The code stub reads the input,
34+
creates a list of Player objects,
35+
uses your method to sort the data, and prints it out properly.
36+
37+
## Example
38+
39+
`n = 3`
40+
`data = [[Smith, 20], [Jones, 15], [Jones, 20]]`
41+
42+
Sort the list as $ data_{sorted} $ = `[Jones, 20], [[Smith, 20], [Jones, 15]]`.
43+
Sort first descending by score, then ascending by name.
44+
45+
## Input Format
46+
47+
The first line contains an integer, `n`, the number of players.
48+
Each of the next `n` lines contains a player's `name` and `score`,
49+
a string and an integer.
50+
51+
## Constraints
52+
53+
- $ 0 \leq score \leq 1000 $
54+
- Two or more players can have the same name.
55+
- Player names consist of lowercase English alphabetic letters.
56+
57+
## Output Format
58+
59+
You are not responsible for printing any output to stdout.
60+
Locked stub code in Solution will instantiate a Checker object,
61+
use it to sort the Player array, and print each sorted element.
62+
63+
## Sample Input
64+
65+
```text
66+
5
67+
amy 100
68+
david 100
69+
heraldo 50
70+
aakansha 75
71+
aleksa 150
72+
```
73+
74+
## Sample Output
75+
76+
```text
77+
aleksa 150
78+
amy 100
79+
david 100
80+
aakansha 75
81+
heraldo 50
82+
```
83+
84+
## Explanation
85+
86+
The players are first sorted descending by score, then ascending by name.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { describe, expect, it } from '@jest/globals';
2+
3+
import {
4+
Player,
5+
SortablePlayer,
6+
comparatorSorting,
7+
comparatorSortingPrint
8+
} from './ctci_comparator_sorting';
9+
import TEST_CASES from './ctci_comparator_sorting.testcases.json';
10+
11+
describe('countSwaps', () => {
12+
it('test_player', () => {
13+
expect.assertions(2);
14+
15+
const aPlayer = new Player('David', 100);
16+
const aPlayerAsString = aPlayer.toString();
17+
const aExpected = '';
18+
19+
expect(aExpected).toStrictEqual(aPlayerAsString);
20+
21+
const bPlayer = new Player('Kurt', 10);
22+
const comparatorAnswerExpected = 0;
23+
24+
expect(aPlayer.comparator(bPlayer)).toStrictEqual(comparatorAnswerExpected);
25+
});
26+
27+
it('test_comparator_sorting', () => {
28+
expect.assertions(8);
29+
30+
TEST_CASES.forEach((test) => {
31+
const players: SortablePlayer[] = [];
32+
33+
for (const player of test.input) {
34+
players.push(new SortablePlayer(player.name, player.score));
35+
}
36+
37+
expect(comparatorSorting(players)).toStrictEqual(test.sorted);
38+
expect(comparatorSortingPrint(players)).toBeUndefined();
39+
});
40+
});
41+
});
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
[
2+
{
3+
"title": "Sample Test Case 0",
4+
"input": [
5+
{
6+
"name": "amy",
7+
"score": 100
8+
},
9+
{
10+
"name": "david",
11+
"score": 100
12+
},
13+
{
14+
"name": "heraldo",
15+
"score": 50
16+
},
17+
{
18+
"name": "aakansha",
19+
"score": 75
20+
},
21+
{
22+
"name": "aleksa",
23+
"score": 150
24+
}
25+
],
26+
"sorted": ["aleksa 150", "amy 100", "david 100", "aakansha 75", "heraldo 50"],
27+
"expected": "aleksa 150\namy 100\ndavid 100\naakansha 75\nheraldo 50"
28+
},
29+
{
30+
"title": "Sample Test Case 6",
31+
"input": [
32+
{
33+
"name": "smith",
34+
"score": 20
35+
},
36+
{
37+
"name": "jones",
38+
"score": 15
39+
},
40+
{
41+
"name": "jones",
42+
"score": 20
43+
}
44+
],
45+
"sorted": ["jones 20", "smith 20", "jones 15"],
46+
"expected": "jones 20\nsmith 20\njones 15"
47+
},
48+
{
49+
"title": "Sample Test Case 7",
50+
"input": [
51+
{
52+
"name": "davis",
53+
"score": 15
54+
},
55+
{
56+
"name": "davis",
57+
"score": 20
58+
},
59+
{
60+
"name": "davis",
61+
"score": 10
62+
},
63+
{
64+
"name": "edgehill",
65+
"score": 15
66+
}
67+
],
68+
"sorted": ["davis 20", "davis 15", "edgehill 15", "davis 10"],
69+
"expected": "davis 20\ndavis 15\nedgehill 15\ndavis 10"
70+
},
71+
{
72+
"title": "Edge case: draw",
73+
"input": [
74+
{
75+
"name": "kurt",
76+
"score": 100
77+
},
78+
{
79+
"name": "kurt",
80+
"score": 100
81+
}
82+
],
83+
"sorted": ["kurt 100", "kurt 100"],
84+
"expected": "kurt 100\nkurt 100"
85+
}
86+
]
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/* eslint-disable class-methods-use-this */
2+
/* eslint-disable @typescript-eslint/no-unused-vars */
3+
/* eslint-disable no-useless-constructor */
4+
/* eslint-disable max-classes-per-file */
5+
/**
6+
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/sort/ctci-comparator-sorting.md]]
7+
*/
8+
9+
// Start Given code
10+
11+
export class Player {
12+
name = '';
13+
14+
score = 0;
15+
16+
toString(): string {
17+
// Given code
18+
return '';
19+
}
20+
21+
comparator(bPlayer: this): number {
22+
// Given code
23+
return 0 * bPlayer.score;
24+
}
25+
}
26+
27+
// End Given code
28+
29+
export class SortablePlayer extends Player {
30+
name = '';
31+
32+
score = 0;
33+
34+
constructor(name: string, score: number) {
35+
super(name, score);
36+
37+
this.name = name;
38+
this.score = score;
39+
}
40+
41+
toString(): string {
42+
return `${this.name} ${this.score}`;
43+
}
44+
45+
comparator(bPlayer: this): number {
46+
if (this.score > bPlayer.score) {
47+
return -1;
48+
}
49+
if (this.score < bPlayer.score) {
50+
return 1;
51+
}
52+
if (this.name < bPlayer.name) {
53+
return -1;
54+
}
55+
if (this.name > bPlayer.name) {
56+
return 1;
57+
}
58+
59+
return 0;
60+
}
61+
}
62+
63+
export function comparatorSorting(players: SortablePlayer[]): string[] {
64+
const sortedPlayers = [...players].sort(
65+
(a: SortablePlayer, b: SortablePlayer): number => a.comparator(b)
66+
);
67+
68+
return sortedPlayers.map((player: SortablePlayer) => player.toString());
69+
}
70+
71+
export function comparatorSortingPrint(players: SortablePlayer[]): void {
72+
console.log(comparatorSorting(players)?.join('\n'));
73+
}
74+
75+
export default { Player, comparatorSorting };

0 commit comments

Comments
 (0)