Problem overview
Five brands have a rating and a review count: TechPro (4, 200), MegaCorp (5, 150), NeoByte (5, 500), Quantum (3, 100) and Zenith (4, 300). The program prints the top k brands, here k = 3, as rank. Brand (rating, reviews):
1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)
The rating decides first. When two brands have the same rating, the one with more reviews wins. If both are equal, the brand listed first wins; the lesson's data has no such pair, but the code follows the rule anyway. The input guarantees that k is never larger than the number of brands.
This version builds on the repeated search from version 4: find the best brand, mark it as taken, search again among the rest. There is no filtering here. Only the comparison changes, because it now has a second criterion.
Approach: a comparison with two criteria
The search keeps best_index, the position of the best brand so far in this round, and found, which says whether a round has picked a brand yet. A vector used flags the winners of earlier rounds so they are skipped.
For each brand that is not used, one of three cases applies, tested in order:
- Nothing has been found yet: this brand is the best so far.
- Its rating is higher than the best one's: it becomes the best, whatever the review counts are.
- Its rating equals the best one's and it has more reviews: it becomes the best.
Because the cases form an else if chain, the third one only runs when the ratings are not different in the brand's favor. Reviews matter only as a tie-breaker. A brand with a lower rating never wins by review count.
When rating and reviews are both equal, none of the cases fires, so best_index keeps the earlier brand. Strict comparisons in cases 2 and 3 give the tie rule for free.
Step by step
- Create
brandswith TechPro, MegaCorp, NeoByte, Quantum and Zenith. - Create
ratingsas 4, 5, 5, 3 and 4. - Create
reviewsas 200, 150, 500, 100 and 300, lined up with the brands by position. - Create
kas 3. - Create
usedwithvec![false; ratings.len()], usinglet mut. - Create
linesas an empty vector withVec::new(). - Loop over the ranks with
for rank in 1..=k. - Create
best_indexinside the loop, starting at 0. - Create
foundinside the loop, starting atfalse. - Open the inner loop over every position
iofratings. - Skip used brands with an
ifon!used[i]. - First case: if nothing is found yet, set
best_indextoiandfoundtotrue. - Second case: an
else iffor a higher rating than the best one's, settingbest_indextoi. - Third case: an
else iffor an equal rating and more reviews, settingbest_indextoi. - After the inner loop, set
used[best_index]totrue. - Add the line to
lineswithpushandformat!: rank, dot, space, brand, then the rating and the review count in parentheses, separated by a comma and a space. - Print after the loop with
lines.join("\n").
The solution in Rust
let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"];
let ratings = vec![4, 5, 5, 3, 4];
let reviews = vec![200, 150, 500, 100, 300];
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 {
best_index = i;
found = true;
} else if ratings[i] > ratings[best_index] {
best_index = i;
} else if ratings[i] == ratings[best_index] && reviews[i] > reviews[best_index] {
best_index = i;
}
}
}
used[best_index] = true;
lines.push(format!("{}. {} ({}, {})", rank, brands[best_index], ratings[best_index], reviews[best_index]));
}
println!("{}", lines.join("\n"));
Rust details worth knowing:
else ifchains are exclusive. Rust runs the first branch whose condition is true and skips the rest. That is why the review comparison can assume the rating is not higher.&&needs both sides. The third case requires equal ratings and more reviews. It short-circuits: when the ratings differ, the review comparison is not evaluated.- Parallel vectors. Nothing in the types ties
brands,ratingsandreviewstogether. The code relies on all three having the same length and order. - A tuple alternative. Rust compares tuples field by field, so
(ratings[i], reviews[i]) > (ratings[best_index], reviews[best_index])expresses the same two-level rule in one test. For example,(5, 500) > (5, 150)istrue. The lesson spells out the cases instead, which makes each rule visible.
Complexity
Time: O(k * n) for n brands, because each of the k rounds scans every brand and each comparison takes constant time. Space: O(n + k) for the used flags and the output lines.
Edge cases and common mistakes
- Reviews beat rating. A brand "Low" with rating 3 and 9000 reviews, and a brand "High" with rating 5 and 1 review, come out as High first, then Low. The rating is compared before the reviews.
- Rating and reviews both equal. Brands P and Q, both rated 4 with 10 reviews, come out as P, then Q. Both comparisons are strict, so the earlier brand stays in front.
- A tie where the last brand has the most reviews. Brands A, B and C, all rated 5, with 1, 2 and 3 reviews, come out as C, B, A.
- A larger
k. Withk = 5on the lesson's data, the lines continue with4. TechPro (4, 200)and5. Quantum (3, 100). - Comparing reviews alone. A rule that looked only at the review counts would rank Zenith (300) above MegaCorp (150), against the lesson's expected output.
Testing
- The lesson's data with
k = 3prints1. NeoByte (5, 500),2. MegaCorp (5, 150)and3. Zenith (4, 300). - The same data with
k = 5adds4. TechPro (4, 200)and5. Quantum (3, 100). - Low (3, 9000) and High (5, 1) with
k = 2print1. High (5, 1)and2. Low (3, 9000). - P (4, 10) and Q (4, 10) with
k = 2print P first.
