Rank the top k brands by rating, breaking ties with the review count. This builds on v4's repeated search (not on v5: there is no filtering here); only the comparison gets a second criterion.
You start with:
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;
Build:
1. NeoByte (5, 500) 2. MegaCorp (5, 150) 3. Zenith (4, 300)
Rules:
- Rating decides first: the higher rating wins.
- If two brands have the same rating, the one with more reviews wins.
- If rating and reviews are both equal, the one listed first wins (the test data has no such pair, but your code must follow the rule).
kis never larger than the number of brands.- Each line is
"rank. Brand (rating, reviews)", starting at rank 1. - Print the lines, one per line, with
println!(...).
Start from v4: the same
let mut used = vec![false; ratings.len()]; and let mut lines = Vec::new();, the same two loops. Only the comparison inside the inner loop changes.
Use a chain (if / else if / else if): no candidate yet, take this one; else a higher rating, take this one; else the same rating and more reviews, take this one.
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"));
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
