Problem overview
Two parallel arrays describe a set of brands: brands holds the names and ratings holds their ratings. The program must print the top k brands by rating, best first, one per line, in the form rank. Brand (rating). Ranks start at 1, and ties go to the brand listed first.
With k = 3 and the starting data, MegaCorp and NeoByte both have rating 5, and MegaCorp is listed first. TechPro and Zenith both have 4, and TechPro is listed first. The output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
The lesson says k is never larger than the number of brands.
Approach: find the best, mark it, search again
Version 3 of this project finds the single best brand: scan every position, remember the best so far and replace it only when a rating is strictly higher. Version 4 repeats that search k times, and each round excludes the brands that already won.
A boolean array named used keeps this memory: used[i] is true once brand i has been given a rank. Each round scans the positions that are not used, picks the best, marks it as used and records its line. The round number is also the rank to print.
The search stores a position, bestIndex, not a rating, because both the name and the rating are read from that position later. The value -1 means that nothing has been found yet in this round.
Sorting the brands would be the other way to get a top k, but sorting two parallel arrays together is awkward, and this lesson practises nested loops.
Step by step
- Create
used.new boolean[ratings.length]gives one flag per brand, allfalseat the start. - Create
lines. AList<String>set to a newArrayListcollects one finished line per rank, starting empty. - Write the outer loop.
rankgoes from 1 up to and includingk, so withk = 3it takes the values 1, 2 and 3. It counts the rounds and is also printed in front of the brand name. - Reset
bestIndex. Inside the round,int bestIndex = -1;starts every search from nothing found. - Write the inner loop.
itakes every position ofratings. For each round of the outer loop, the inner one runs through all the brands from the start. That is what makes the loops nested. - Skip taken brands. An
if (!used[i])makes only the brands without a rank candidates. - Compare. Inside it, a second
ifis true when nothing is found yet (bestIndex == -1) or when this rating is strictly higher than the best one's. The strict comparison leaves a tie with the earlier brand. - Remember the brand. Set
bestIndextoi. - Mark the winner. After the inner loop, set
used[bestIndex]totrue, so the next round can't pick it again. - Add the line. Build it as the rank, a dot and a space, the brand's name, then the rating in parentheses, and add it to
lines. Java's+turns theintvalues into text when it joins them to aString. - Print. After the loop,
String.join("\n", lines)glues the lines together with a newline between each two, andSystem.out.printlnprints the result.
The solution in Java
String[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
int[] ratings = {4, 5, 3, 5, 4};
int k = 3;
boolean[] used = new boolean[ratings.length];
List<String> lines = new ArrayList<>();
for (int rank = 1; rank <= k; rank++) {
int bestIndex = -1;
for (int i = 0; i < ratings.length; i++) {
if (!used[i]) {
if (bestIndex == -1 || ratings[i] > ratings[bestIndex]) {
bestIndex = i;
}
}
}
used[bestIndex] = true;
lines.add(rank + ". " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
}
System.out.println(String.join("\n", lines));
The Java details worth a closer look:
rank + ". " + .... The expression starts with anint, but the next operand is a string, so from there on everything is joined as text. The result is1. MegaCorp (5).String.join. It takes a separator and an iterable of strings, here the list. There is no separator after the last line, so the output has no blank line at the end.- Short-circuit
||. WhenbestIndexis -1, the right side is not evaluated, soratings[-1]is never read. - Default flags. A new
boolean[]starts allfalse, which is what "nobody has a rank yet" needs.
Complexity
Time: O(k * n) for n brands. Each of the k rounds scans all n positions. With k as large as n this is O(n²).
Space: O(n + k): the used flags take n slots, and lines holds k strings.
Edge cases and common mistakes
- Ties. The strict
>keeps the first brand. With>=the starting data would print NeoByte first, then MegaCorp, then Zenith. The expected order is MegaCorp, NeoByte, TechPro. kequal to the number of brands. Withk = 5the output is MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4) and Quantum (3), each on its own line.k = 1. The output is the single line1. MegaCorp (5).klarger than the number of brands. The lesson rules this out. If it happened, a round with no brand left would leavebestIndexat -1, andused[-1]would throwArrayIndexOutOfBoundsException. Withk = 6on the five starting brands the message isIndex -1 out of bounds for length 5.- Forgetting to mark the winner. Without
used[bestIndex] = true, every round finds the same brand. - Declaring
bestIndexoutside the outer loop. A stale index from the last round would be compared in the next one. - Printing inside the loop. The lesson collects the lines and prints once with
String.join. Printing inside the loop gives the same lines, but the collected form keeps the output code in one place.
Testing
k = 1gives1. MegaCorp (5).k = 3gives the three lines above.k = 5gives five lines, ending with5. Quantum (3).
