Ordering with ties
Write one comparison rule that every part of the code agrees on.
Define the order once
Leaderboards, schedulers and booking queues all need an order with tie-breakers: score then name, time then priority then arrival. Write that rule as one function and use it everywhere.
When top() and rank() each sort their own way, they disagree on ties and tests catch it.
const byRank = (a: Entry, b: Entry) =>
b.score - a.score || a.player.localeCompare(b.player);
Stable tie-breaks need a key
"In the order they were added" needs a sequence number stored on each item, because heaps do not keep insertion order on their own.
Key takeaways
- One comparison function, used everywhere.
- Spell out every tie-breaker.
- Insertion order needs a stored sequence number.
Hands-on coding exercise
Keep each player's best score and list the top k: highest score first, and on a tie, names in alphabetical order.
Write the tie-break into the comparison so the order is always the same.
class Scoreboard {
/** Records a score; a player keeps their best */
add(name: string, score: number): void {
throw new Error("Not implemented");
}
top(k: number): string[] {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- Two jobs have the same run time and priority. How do you keep scheduling order in a heap?
- Why put the ordering rule in one function?