Priority ticket order
A support queue lists a unique ticket ID and priority 1, 2 or 3 for each ticket. Print IDs in service order: highest priority first, then alphabetical ID for ties. Do not assume input order already expresses priority, and do not compare numeric priorities as strings.
Input
First line N; then N id priority lines.
Output
One ticket ID per line in service order.
Example 1
Input
4 z 2 a 3 c 2 b 3
Output
a b c z
Priority three tickets A and B come first in ID order, then priority two tickets C and Z.
Constraints
- 1 <= N <= 200; ticket IDs are unique.
- Priority is an integer from 1 through 3.
Hints
Hint 1 of 2
Convert priority to Number before sorting.
Hint 2 of 2
Use a two-part comparator: descending priority, ascending ID.
Solution
Show a reference solution and explanation
const n = Number(readline());
const rows = [];
for (let i = 0; i < n; i++) {
const [id, priority] = readline().split(' ');
rows.push({ id, priority: Number(priority) });
}
rows.sort((a, b) => b.priority - a.priority || a.id.localeCompare(b.id));
for (const row of rows) console.log(row.id);
Why it works
The comparator subtracts numeric priorities to put 3 before 2 before 1. When priorities match, localeCompare gives the stated alphabetical ID tie-break. Sorting once produces a deterministic queue even when the input is shuffled.
Lesson for this exercise: JavaScript Arrays: Creating, Indexing and Changing Lists