Skip to content

Commit acd4158

Browse files
authored
Merge pull request #455 from sir-gon/feature/ctci-comparator-sorting
[Hacker Rank] Interview Preparation Kit: Sorting: Comparator. Solved ✅.
2 parents 76db312 + 43478fc commit acd4158

File tree

6 files changed

+297
-5
lines changed

6 files changed

+297
-5
lines changed

.github/workflows/eslint.yml

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,20 @@ jobs:
4545

4646
- name: Install ESLint
4747
run: |
48-
npm install [email protected]
49-
npm install @microsoft/[email protected]
50-
48+
npm install --include=dev [email protected]
49+
npm install --include=dev @microsoft/[email protected]
50+
- name: Test ESLint
51+
run: |
52+
npx --yes eslint --env-info
5153
- name: Run ESLint
52-
run: npx eslint .
54+
run: >
55+
npx eslint .
5356
--config .eslintrc
57+
--max-warnings=0
5458
--ext .js,.jsx,.ts,.tsx
5559
--format @microsoft/eslint-formatter-sarif
5660
--output-file eslint-results.sarif
5761
continue-on-error: true
58-
5962
- name: Upload analysis results to GitHub
6063
uses: github/codeql-action/upload-sarif@v3
6164
with:
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: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Start Given code
2+
3+
export class Player {
4+
name = '';
5+
6+
score = 0;
7+
8+
toString(): string {
9+
// Given code
10+
this.name.toString();
11+
return '';
12+
}
13+
14+
comparator(bPlayer: this): number {
15+
// Given code
16+
return 0 * this.score * bPlayer.score;
17+
}
18+
}
19+
20+
// End Given code
21+
22+
export default { Player };
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { describe, expect, it } from '@jest/globals';
2+
3+
import { Player } from './ctci_comparator_sorting.Player';
4+
5+
import {
6+
SortablePlayer,
7+
comparatorSorting,
8+
comparatorSortingPrint
9+
} from './ctci_comparator_sorting';
10+
import TEST_CASES from './ctci_comparator_sorting.testcases.json';
11+
12+
describe('countSwaps', () => {
13+
it('test_player', () => {
14+
expect.assertions(2);
15+
16+
const aPlayer = new Player();
17+
const aPlayerAsString = aPlayer.toString();
18+
const aExpected = '';
19+
20+
expect(aExpected).toStrictEqual(aPlayerAsString);
21+
22+
const bPlayer = new Player();
23+
const comparatorAnswerExpected = 0;
24+
25+
expect(aPlayer.comparator(bPlayer)).toStrictEqual(comparatorAnswerExpected);
26+
});
27+
28+
it('test_comparator_sorting', () => {
29+
expect.assertions(8);
30+
31+
TEST_CASES.forEach((test) => {
32+
const players: SortablePlayer[] = [];
33+
34+
for (const player of test.input) {
35+
players.push(new SortablePlayer(player.name, player.score));
36+
}
37+
38+
expect(comparatorSorting(players)).toStrictEqual(test.sorted);
39+
expect(comparatorSortingPrint(players)).toBeUndefined();
40+
});
41+
});
42+
});
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: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/sort/ctci-comparator-sorting.md]]
3+
*/
4+
5+
import { Player } from './ctci_comparator_sorting.Player';
6+
7+
export class SortablePlayer extends Player {
8+
name = '';
9+
10+
score = 0;
11+
12+
constructor(name: string, score: number) {
13+
super();
14+
15+
this.name = name;
16+
this.score = score;
17+
}
18+
19+
toString(): string {
20+
return `${this.name} ${this.score}`;
21+
}
22+
23+
comparator(bPlayer: this): number {
24+
if (this.score > bPlayer.score) {
25+
return -1;
26+
}
27+
if (this.score < bPlayer.score) {
28+
return 1;
29+
}
30+
if (this.name < bPlayer.name) {
31+
return -1;
32+
}
33+
if (this.name > bPlayer.name) {
34+
return 1;
35+
}
36+
37+
return 0;
38+
}
39+
}
40+
41+
export function comparatorSorting(players: SortablePlayer[]): string[] {
42+
const sortedPlayers = [...players].sort(
43+
(a: SortablePlayer, b: SortablePlayer): number => a.comparator(b)
44+
);
45+
46+
return sortedPlayers.map((player: SortablePlayer) => player.toString());
47+
}
48+
49+
export function comparatorSortingPrint(players: SortablePlayer[]): void {
50+
console.log(comparatorSorting(players)?.join('\n'));
51+
}
52+
53+
export default { Player, SortablePlayer, comparatorSorting };

0 commit comments

Comments
 (0)