Problem overview
Version 4 ranks the top k brands by rating. The data is in two parallel arrays, brands and ratings, where ratings[i] belongs to brands[i], and k says how many brands to show. Each output line has the form rank. Brand (rating), starting at rank 1.
For the starter data, brands ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"] with ratings [4, 5, 3, 5, 4] and k = 3, the output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
MegaCorp and NeoByte both have rating 5, and MegaCorp is listed first, so it is rank 1. TechPro and Zenith tie at 4, and TechPro is listed first, so it takes rank 3. The lesson guarantees that k is never larger than the number of brands.
Approach: find the best, mark it, repeat
Version 3 found the single best brand with one scan. Version 4 repeats that scan once per rank. The only change is that a brand already placed must not win again, so the program keeps an array used, with one boolean per brand: used[i] is true after brand i has been given a rank.
Each round starts with bestIndex = -1, meaning "nothing found yet". The inner loop looks at every brand that isn't used. The first one it sees becomes the best, and a later one replaces it only when its rating is strictly higher. Strictly higher is what makes ties go to the brand listed first. After the scan, the winner is marked as used and its line is added to an array lines.
The cost is k scans of n brands: O(k * n) time, plus O(n) space for used. Sorting would be an alternative, but this lesson practises nested loops.
The three rounds on the starter data
| rank | Brands still available | Winner |
|---|---|---|
| 1 | all five | MegaCorp (5): NeoByte ties at 5 but is not strictly higher |
| 2 | all but MegaCorp | NeoByte (5) |
| 3 | TechPro, Quantum, Zenith | TechPro (4): Zenith ties at 4 but is not strictly higher |
After round 3 the loop ends, and Quantum and Zenith never receive a rank because only k = 3 lines were asked for.
Step by step
- Create
usedwith onefalseper rating, usingnew Array(ratings.length).fill(false). - Create
linesas an empty array. One finished line will be added per round. - Write the outer loop with
rankfrom 1 up to and includingk. Starting at 1 makesrankdouble as the number printed in front of the brand. - Set
bestIndexto -1 inside it, so every round starts the search over. - Write the inner loop with
iover every position ofratings. - Skip used brands with
if (!used[i]). - Test for a new best: inside it, an
ifthat is true whenbestIndexis -1 orratings[i]is strictly higher thanratings[bestIndex]. - Remember the brand by setting
bestIndextoi. - Mark the winner after the inner loop:
used[bestIndex] = true. - Add the line with
push: the rank, a dot and a space, the brand's name, then the rating in parentheses. - Print
lines.join("\n")after the loops, so each line ends up on its own row.
The solution in JavaScript
const brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
const ratings = [4, 5, 3, 5, 4];
const k = 3;
const used = new Array(ratings.length).fill(false);
const lines = [];
for (let rank = 1; rank <= k; rank++) {
let bestIndex = -1;
for (let i = 0; i < ratings.length; i++) {
if (!used[i]) {
if (bestIndex === -1 || ratings[i] > ratings[bestIndex]) {
bestIndex = i;
}
}
}
used[bestIndex] = true;
lines.push(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
}
console.log(lines.join("\n"));
The details to notice:
new Array(n).fill(false).new Array(n)alone makes empty slots.fill(false)gives each a realfalse.- Building text with
+. When one side is a string, JavaScript converts the number on the other side, sorank + ". " + ...produces"1. MegaCorp (5)". The first+has a number on its left and a string on its right, so it joins rather than adds. join("\n"). It glues the array's strings together with a newline between each pair, with none after the last one. A singleconsole.logthen prints every rank on its own line.- Collect, then print once. The lines are stored in an array and printed together at the end, instead of printing inside the loop. The program then produces its whole output in one
console.logcall, and you could still sort, count or check the lines before printing them. bestIndexholds a position, not a value. The position works in both arrays, so one variable gives the name and the rating.
Edge cases and common mistakes
- Ties. Using
>=instead of>makes the later brand replace the earlier one. For the starter data NeoByte would take rank 1 instead of MegaCorp. - Forgetting to mark the winner. Without
used[bestIndex] = true, every round would return MegaCorp. - Placing
bestIndex = -1before the outer loop. The previous winner's index would carry into the next round, and the search would not start from scratch. kequal to the number of brands. Withk = 5every brand gets a rank, from MegaCorp, NeoByte, TechPro and Zenith down to Quantum.klarger than the number of brands. The lesson promises this doesn't happen. If it did,bestIndexwould stay -1 in the extra rounds, and the program would print a line such as6. undefined (undefined).k = 0. The loop doesn't run,linesis empty, andjoingives an empty string, so a blank line is printed.
Testing
- The starter data with
k = 3prints MegaCorp (5), NeoByte (5) and TechPro (4) as ranks 1 to 3. k = 1prints only1. MegaCorp (5).k = 5prints MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3).
