Unique parcel register
A parcel register receives N lines intended to contain id quantity. Accept a row only when it has exactly two fields, its ID has not appeared in any previously accepted row, and quantity is a positive whole integer. Reject malformed, duplicate and non-positive rows without changing the accepted register. Print accepted records sorted by ID, then the rejected count.
Input
First line N; then N lines intended as id quantity. IDs are single lowercase tokens.
Output
Sorted id quantity lines followed by rejected X.
Example 1
Input
5 box 3 bag 2 box 5 bad x crate 1
Output
bag 2 box 3 crate 1 rejected 2
Box is accepted only on its first row, the non-numeric row is rejected, and the accepted IDs print alphabetically.
Constraints
- 0 <= N <= 200 records.
- IDs are non-empty lowercase tokens; accepted quantities are positive safe integers.
Hints
Hint 1 of 2
Check the entire quantity token before Number conversion.
Hint 2 of 2
Insert only after every rule passes, so a rejected ID can be used later.
Solution
Show a reference solution and explanation
const n = Number(readline());
const accepted = new Map();
let rejected = 0;
for (let i = 0; i < n; i++) {
const fields = readline().split(' ');
const id = fields[0], token = fields[1];
const quantity = Number(token);
if (fields.length !== 2 || !/^\d+$/.test(token || '') || !Number.isSafeInteger(quantity) || quantity <= 0 || accepted.has(id)) {
rejected++;
continue;
}
accepted.set(id, quantity);
}
for (const id of [...accepted.keys()].sort()) console.log(id, accepted.get(id));
console.log('rejected', rejected);
Why it works
The Map records only accepted IDs. Shape, numeric syntax, safe integer range, positivity and uniqueness are checked before insertion, so rejected rows never corrupt state. Alphabetical output and a rejected count make the import auditable.
Lesson for this exercise: Error Handling in JavaScript