Problem overview
Five brands have ratings: TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4. The program prints the top k brands in rank order, here with k = 3, one per line as rank. Brand (rating):
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
Ties go to the brand listed first, so MegaCorp precedes NeoByte, and TechPro precedes Zenith. The input guarantees that k is never larger than the number of brands.
The previous version found the single best brand with one scan. This version repeats that scan k times, setting each winner aside so the next round finds the next best.
Approach: search, mark, search again
The program keeps one flag per brand in a vector used, all false at the start. A round looks only at brands whose flag is false and picks the one with the highest rating. It then flips the winner's flag to true, so the following rounds skip it.
Within a round, the search keeps the position of the best brand so far in best_index. A second variable, found, says whether the round has picked anything yet. Without it, starting best_index at 0 would be wrong when brand 0 is already taken: the loop would compare against a used brand. In some languages a position of -1 means "none", but a Rust index can't be negative, so a flag does the job.
A brand replaces the current best only when its rating is strictly higher. A tie keeps the earlier brand, which is the rule. Each finished round adds one text line to a vector, and a final join prints them all.
Step by step
- Create
brandswith the five names, in the given order. - Create
ratingsas 4, 5, 3, 5, 4, so each rating lines up with its brand. - Create
kas 3. - Create
usedwithvec![false; ratings.len()], usinglet mut. - Create
linesas an empty vector withVec::new(), alsolet mut. - Loop over the ranks with
for rank in 1..=k. The range includesk, sorankis 1, 2 and 3, and it is also the number printed in front of the brand. - Create
best_indexinside the loop, starting at 0, so every round starts fresh. - Create
foundinside the loop, starting atfalse. - Open the inner loop over every position
iofratings. - Skip taken brands with an
ifthat is true whenused[i]is false. - Test for a new best with a second
if: nothing found yet, or a strictly higher rating than the best one's. - Remember the brand by setting
best_indextoi. - Record the find by setting
foundtotrue. - After the inner loop, set
used[best_index]totrue. - Add the round's line to
lineswithpushandformat!: the rank, a dot and a space, the brand, and the rating in parentheses. - Print after the loop with
lines.join("\n")insideprintln!.
The solution in Rust
let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
let ratings = vec![4, 5, 3, 5, 4];
let k = 3;
let mut used = vec![false; ratings.len()];
let mut lines = Vec::new();
for rank in 1..=k {
let mut best_index = 0;
let mut found = false;
for i in 0..ratings.len() {
if !used[i] {
if !found || ratings[i] > ratings[best_index] {
best_index = i;
found = true;
}
}
}
used[best_index] = true;
lines.push(format!("{}. {} ({})", rank, brands[best_index], ratings[best_index]));
}
println!("{}", lines.join("\n"));
Rust details worth knowing:
- Inclusive range.
1..=kincludesk, while0..ratings.len()stops before the length. The first gives ranks, the second gives positions. - Inferred types.
linesstarts asVec::new()with no element type. The firstpushof aStringfromformat!tells Rust it is aVec<String>. Thenjoin("\n")glues the strings with a newline between each two and no newline after the last. format!againstprintln!. Both use the same{}placeholders, butformat!returns aStringinstead of printing it.- Index types.
best_indexstarts as 0 and is used to index vectors, so Rust makes it ausize. The loop variableiis ausizetoo.
Complexity
Time: O(k * n) for n brands, because each of the k rounds scans all of them. Space: O(n + k) for the used flags and the k output lines.
Edge cases and common mistakes
- Different values of
k.k = 1prints only1. MegaCorp (5).k = 5prints all five brands: MegaCorp, NeoByte, TechPro, Zenith and Quantum with ratings 5, 5, 4, 4 and 3. Withk = 0the loop doesn't run,linesis empty, andprintln!prints an empty line. - Ties. Brands X, Y and Z, all rated 3, with
k = 3come out as X, Y, Z. The strict>keeps the earlier brand in front. With>=a later brand would replace it. - A single brand. Brand
Solorated 2 withk = 1prints1. Solo (2). klarger than the number of brands. The lesson rules it out, and the code doesn't check for it. Two brands A (1) and B (2) withk = 3print1. B (2),2. A (1)and then3. A (1): in the third round nothing is left, sobest_indexstays at 0 and brand 0 repeats.- Not marking the winner. Without
used[best_index] = true, every round finds MegaCorp again. - Dropping the
foundflag. A comparison that starts frombest_index = 0would compare against a brand that may be taken already.
Testing
- The lesson's data with
k = 3prints1. MegaCorp (5),2. NeoByte (5)and3. TechPro (4). k = 1prints1. MegaCorp (5).k = 5prints all five brands, ending with5. Quantum (3).- One brand
Solowith rating 2 andk = 1prints1. Solo (2).
