Problem overview
The catalog now covers several products. The starter code has three parallel arrays, products, brands and ratings, where row i says that brand i sells product i with rating i. It also has a target product, here "Laptop", and a number k, here 2.
The program first keeps only the rows whose product equals target. Then it ranks the top k of them by rating, highest first, and prints each as rank. Brand (rating). Ties go to the entry listed first. If fewer than k rows match, only the existing ones are printed. For the starter data the three laptop brands are TechPro (4), NeoByte (5) and AlphaTech (4), so the output is:
1. NeoByte (5)
2. TechPro (4)
Approach
There are two phases. The first is a filter: one pass over the catalog copies the brand and the rating of every matching row into two new lists, keeping the original order. The second is the repeated search from the previous version, run on the filtered lists: k rounds, each finding the best brand not yet taken by a strict comparison, and marking it.
Filtering first matters because the ranking should only see the target product. Brands that sell phones or tablets must not take a rank, however high their rating is: MegaCorp has a 5 for a phone, but it doesn't appear in the laptop ranking.
The filtered lists need to grow as matches are found, and their final size isn't known in advance, so they are ArrayBuffer values instead of fixed-size arrays. Because the brand and its rating are appended together, they stay at the same position in both lists.
Step by step
- Create
filteredBrands, an emptyArrayBuffer[String]. - Create
filteredRatings, an emptyArrayBuffer[Int], for the matching ratings. - Loop over the catalog.
for (i <- 0 until products.size)visits every row. - Test the product.
if (products(i) == target). In Scala==compares the text of two strings, not their identity. - Append the brand to
filteredBrands. - Append the rating to
filteredRatings, in the same order. - Create
used, sized by the filtered ratings:Array.fill(filteredRatings.size)(false). Its length is the number of matches, not the size of the catalog. - Create
lines, an emptyArrayBuffer[String], for the output. - Loop over the ranks with
for (rank <- 1 to k). - Set
bestIndexto -1 at the start of each round. - Nest a loop over the positions of
filteredRatings. - Skip taken entries with
if (!used(i)). - Compare strictly: nothing found yet, or a higher rating than the best one's.
- Remember it:
bestIndex = i. - Check a brand was found with
bestIndex != -1, because a round can run out of brands. - Mark the winner as used.
- Append the line, built from the rank, the brand and the rating.
- Print the lines joined with newlines.
The solution in Scala
val products = Array("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
val ratings = Array(4, 5, 5, 3, 4, 4)
val target = "Laptop"
val k = 2
val filteredBrands = scala.collection.mutable.ArrayBuffer[String]()
val filteredRatings = scala.collection.mutable.ArrayBuffer[Int]()
for (i <- 0 until products.size) {
if (products(i) == target) {
filteredBrands.append(brands(i))
filteredRatings.append(ratings(i))
}
}
val used = Array.fill(filteredRatings.size)(false)
val lines = scala.collection.mutable.ArrayBuffer[String]()
for (rank <- 1 to k) {
var bestIndex = -1
for (i <- 0 until filteredRatings.size) {
if (!used(i)) {
if (bestIndex == -1 || filteredRatings(i) > filteredRatings(bestIndex)) {
bestIndex = i
}
}
}
if (bestIndex != -1) {
used(bestIndex) = true
lines.append(rank.toString() + ". " + filteredBrands(bestIndex) + " (" + filteredRatings(bestIndex) + ")")
}
}
println(lines.mkString("\n"))
Details that matter in Scala
Inside the loops, filteredRatings(i) reads an ArrayBuffer with parentheses, just as it does with an array, and append adds an element at the end. The line is built with rank.toString() + ". " + filteredBrands(bestIndex) + " (" + filteredRatings(bestIndex) + ")". rank.toString() turns the Int into text, and the + operator joins it with the other pieces; the numeric rating is converted to text the same way when it follows a string.
The positions in used and bestIndex refer to the filtered lists, not to the catalog. The brand at filtered position 1 is NeoByte, even though it sits at position 2 in the original catalog. Mixing the two kinds of index is a classic source of wrong output.
Edge cases and common mistakes
- More
kthan matches. Withk= 3 the laptop ranking has three lines: NeoByte (5), TechPro (4) and AlphaTech (4). Withk= 5 it still has just these three, because the last two rounds find no brand and thebestIndex != -1check keeps them silent. - One match. For
"Tablet"andk= 2, only1. Quantum (3)prints. - No match. For a product that isn't in the catalog, such as
"Watch", the lines buffer stays empty andprintlnprints one blank line. - Case matters.
"laptop"in lowercase doesn't equal"Laptop", so it matches nothing and prints a blank line. - Phones. For
"Phone"andk= 2 the output is1. MegaCorp (5)and2. Zenith (4). - Ties. TechPro and AlphaTech both have a 4 for laptops, and TechPro is listed first, so it ranks above AlphaTech.
Complexity
The filter pass is O(n) for n catalog rows. If m rows match, the search costs O(k * m). The two filtered buffers and the used array take O(m) space.
Key takeaways
- Filter first, then rank: the ranking sees only the rows that match.
- Append related values to separate buffers in the same order to keep their positions aligned.
- Guard each round with
bestIndex != -1when there may be fewer thankcandidates.
