The full catalog covers many products. Filter to one product first, then rank the top k brands that sell it, using v4's repeated search on the filtered lists.
You start with: an empty editor (no starter code). Declare this data yourself:
let products = vec!["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
let ratings = vec![4, 5, 5, 3, 4, 4];
let target = "Laptop";
let k = 2;
Build:
1. NeoByte (5) 2. TechPro (4)
Rules:
- Filter: copy the brand and the rating of every row whose product equals
targetinto two new lists, keeping the order. - From the filtered lists pick the top
kby rating, highest first, with v4's repeated search. Ties go to the entry listed first. - If fewer than
kproducts match, list only those that exist: when no brand is left, add no more lines (no extra lines, no error). - Each line is
"rank. Brand (rating)", starting at rank 1. - Print the lines, one per line, with
println!(...).
Build
filtered_brands and filtered_ratings first: a loop over the catalog that copies the row when products[i] == target.
Then run v4's repeated search over the filtered lists (same code, new names).
If fewer than
k products match, some round finds nobody (found stays false): add a line only when a brand was found.
let products = vec!["Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop"];
let brands = vec!["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech"];
let ratings = vec![4, 5, 5, 3, 4, 4];
let target = "Laptop";
let k = 2;
let mut filtered_brands = Vec::new();
let mut filtered_ratings = Vec::new();
for i in 0..products.len() {
if products[i] == target {
filtered_brands.push(brands[i]);
filtered_ratings.push(ratings[i]);
}
}
let mut used = vec![false; filtered_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..filtered_ratings.len() {
if !used[i] {
if !found || filtered_ratings[i] > filtered_ratings[best_index] {
best_index = i;
found = true;
}
}
}
if found {
used[best_index] = true;
lines.push(format!("{}. {} ({})", rank, filtered_brands[best_index], filtered_ratings[best_index]));
}
}
println!("{}", lines.join("\n"));
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
