Problem overview
The starter code has three parallel arrays, brands, ratings and reviews, and a number k, here 3. The program ranks the top k brands. Rating decides first: the higher rating wins. When two brands have the same rating, the one with more reviews wins. If both are equal, the one listed first wins. Each line has the form rank. Brand (rating, reviews). The value of k is never larger than the number of brands.
For the starter data the output is:
1. NeoByte (5, 500)
2. MegaCorp (5, 150)
3. Zenith (4, 300)
NeoByte and MegaCorp both have a 5, and NeoByte has more reviews. Zenith and TechPro both have a 4, and Zenith's 300 reviews beat TechPro's 200.
Approach
The method is the repeated search used for plain top-k: k rounds, each scanning the brands that aren't taken, keeping the index of the best, and marking the winner. The only change is the test that decides whether a candidate replaces the current best. It now has three cases, checked in order:
- Nothing is chosen yet, so the candidate is the best so far.
- The candidate's rating is higher, so it wins, whatever the reviews are.
- The ratings are equal and the candidate has more reviews, so it wins.
Every other candidate leaves the best unchanged. That includes a candidate that ties on both values, and that is exactly how a tie on rating and reviews goes to the brand listed first: the later brand doesn't replace the earlier one.
The order of the cases is what makes the rating more important than the reviews. A brand with a low rating and many reviews never gets to the review comparison, because its rating is neither higher nor equal. For two brands, Low (rating 3, 9000 reviews) and High (rating 5, 1 review), the ranking is High first, then Low.
Step by step
- Create
usedwithArray.fill(ratings.size)(false), one flag per brand. - Create
lines, an emptyArrayBuffer[String]. - 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
ratings. - Skip the taken brands with
if (!used(i)). - First case: if
bestIndexis -1, set it toi. - Second case with
else if: the rating is higher than the best one's. - Third case with another
else if: the ratings are equal and the reviews are higher. - Mark the winner after the inner loop:
used(bestIndex) = true. - Append the line with the rank, the name, then the rating and the review count in parentheses, separated by a comma and a space.
- Print the lines joined by newlines.
The solution in Scala
val brands = Array("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith")
val ratings = Array(4, 5, 5, 3, 4)
val reviews = Array(200, 150, 500, 100, 300)
val k = 3
val used = Array.fill(ratings.size)(false)
val lines = scala.collection.mutable.ArrayBuffer[String]()
for (rank <- 1 to k) {
var bestIndex = -1
for (i <- ratings.indices) {
if (!used(i)) {
if (bestIndex == -1) {
bestIndex = i
}
else if (ratings(i) > ratings(bestIndex)) {
bestIndex = i
}
else if (ratings(i) == ratings(bestIndex) && reviews(i) > reviews(bestIndex)) {
bestIndex = i
}
}
}
used(bestIndex) = true
lines.append(s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)}, ${reviews(bestIndex)})")
}
println(lines.mkString("\n"))
Details that matter in Scala
The three cases are an if / else if chain, so only the first true one runs. The first case has to come first: when bestIndex is -1, the later cases would call ratings(bestIndex) and fail with an index error. Because of the chain, they are never evaluated in that situation.
The condition ratings(i) == ratings(bestIndex) && reviews(i) > reviews(bestIndex) needs both parts. In Scala, == on Int compares values, as you would hope. The third case does not repeat the check for a higher rating, since the second case has already taken that one.
The string s"$rank. ${brands(bestIndex)} (${ratings(bestIndex)}, ${reviews(bestIndex)})" uses braces around every placeholder that is an index expression. $rank is a plain name, so it needs none. The dot after it ends the name, so it isn't swallowed by the placeholder.
Edge cases and common mistakes
- More reviews, same rating. For A, B and C with ratings 4, 4, 4 and reviews 10, 30, 20, the order is B (30), C (20), A (10).
- A complete tie. With P, Q and R all at 4 and 10 reviews, the output keeps the listed order: P, Q, R. Two brands with equal values are never swapped.
- Using
>=for reviews. This would let a later brand with equal reviews replace the earlier one and break the rule that the earlier brand wins. - Comparing reviews first. A brand with 9000 reviews and a 3 would then outrank a 5. The rating has to come first.
kequal to the number of brands. Withk= 5, the starter data ranks NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200) and Quantum (3, 100). Withk= 1 only NeoByte prints.- Combining the criteria in one number. Adding rating and reviews would be wrong, as the two values aren't comparable.
Complexity
Each of the k rounds scans all n brands in constant time per brand, so the time is O(k * n). The extra space is the used array and the lines buffer.
Key takeaways
- A tie-break is a second condition checked only when the first one is equal.
- An
else ifchain evaluates the cases in order, so put the main criterion before the secondary one. - Keeping the earlier item on a full tie needs strict comparisons.
