Problem overview
The catalog now lists many products. Row i of three parallel structures describes one entry: products[i] is the product, brands[i] the brand that sells it and ratings[i] its rating. The program keeps only the rows whose product equals target, then prints the top k of them by rating as rank. Brand (rating). Ties go to the entry listed first.
The starter code:
val products = arrayOf("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
val ratings = intArrayOf(4, 5, 5, 3, 4, 4)
val target = "Laptop"
val k = 2
Three rows sell a Laptop: TechPro (4), NeoByte (5) and AlphaTech (4). The two best are NeoByte and then TechPro, which is listed before AlphaTech:
1. NeoByte (5)
2. TechPro (4)
If fewer than k rows match, the program lists only the ones that exist, with no extra lines and no error.
Approach
The work splits into two parts. First, filter: copy the brand and the rating of every matching row into two new lists, in the same order, so the position in one list still matches the position in the other. Second, run the previous version's repeated search on those filtered lists: each round picks the best brand not taken yet, marks it in a used array, and adds a line.
The filtered lists must be real lists that grow, because nobody knows in advance how many rows match. That is why they are mutableListOf lists and not arrays. The search then uses their sizes, not the sizes of the original arrays. For the lesson's data the filtered lists are [TechPro, NeoByte, AlphaTech] and [4, 5, 4].
There is one new situation compared with the previous version. When fewer than k brands match, a round can find nobody, so bestIndex is still -1 after the inner loop. The program must check for that before using it.
Step by step
- Create
filteredBrands, an emptymutableListOf<String>(). - Create
filteredRatings, an emptymutableListOf<Int>(). - Loop over every row.
itakes each position ofproducts, and the three arrays line up at that position. - Test the product. An
ifchecksproducts[i] == target, so other rows are skipped. - Copy the brand into
filteredBrandswithadd. - Copy the rating into
filteredRatingsthe same way, so both lists keep the same order. - Create
usedafter the loop, sized to the filtered ratings, not to the original arrays. - Create
lines, an empty list of strings for the finished lines. - Loop over the ranks with
for (rank in 1..k). - Reset
bestIndexto -1 in every round. - Write the inner loop over the positions of
filteredRatings. - Skip taken entries by testing
!used[i]. - Compare. An entry becomes the best when nothing is found yet or its rating is strictly higher.
- Remember it by setting
bestIndex = i. - Guard against an empty round. After the inner loop, continue only when
bestIndex != -1. - Mark the winner with
used[bestIndex] = true. - Add the line to
lines: the rank, a dot and a space, the brand, and the rating in parentheses. - Print the lines joined with newlines.
The solution in Kotlin
val products = arrayOf("Laptop", "Phone", "Laptop", "Tablet", "Phone", "Laptop")
val brands = arrayOf("TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith", "AlphaTech")
val ratings = intArrayOf(4, 5, 5, 3, 4, 4)
val target = "Laptop"
val k = 2
val filteredBrands = mutableListOf<String>()
val filteredRatings = mutableListOf<Int>()
for (i in 0 until products.size) {
if (products[i] == target) {
filteredBrands.add(brands[i])
filteredRatings.add(ratings[i])
}
}
val used = BooleanArray(filteredRatings.size)
val lines = mutableListOf<String>()
for (rank in 1..k) {
var bestIndex = -1
for (i in 0 until filteredRatings.size) {
if (!used[i]) {
if (bestIndex == -1 || filteredRatings[i] > filteredRatings[bestIndex]) {
bestIndex = i
}
}
}
if (bestIndex != -1) {
used[bestIndex] = true
lines.add(rank.toString() + ". " + filteredBrands[bestIndex] + " (" + filteredRatings[bestIndex] + ")")
}
}
println(lines.joinToString("\n"))
Kotlin details worth a look:
==compares contents.products[i] == targetcallsequalson the strings, so it is true for two differentStringobjects holding the same text. It is case sensitive: atargetof"laptop"matches nothing here.- Two inner loops, two index names. Both loops call their variable
i. That is fine, because the first loop has finished before the second starts, and eachiexists only inside its own loop. sizeon lists and arrays. Arrays and lists both have asizeproperty. The search loop usesfilteredRatings.size, the number of matches, notratings.size.- Building the line with
+.rankis anInt, sorank.toString()comes first to start aString. After that,+converts each number it meets on the right-hand side. List<Int>boxes its numbers. AMutableList<Int>holds boxed integers, unlikeIntArray. For this lesson's sizes that makes no difference.
Complexity
Time: O(n + k * m), where n is the number of rows and m the number of matches. The filter scans the n rows once, and then each of the k rounds scans the m filtered entries. Space: O(m) for the filtered lists and the used flags, plus O(k) for the lines.
Edge cases and common mistakes
- Fewer matches than
k. Withtarget = "Tablet"andk = 3, only1. Quantum (3)prints. With"Laptop"andk = 5the three Laptop lines print and rounds 4 and 5 add nothing. - No match at all. With
target = "Desktop"every round finds nobody,linesstays empty, andprintlnprints an empty line. There is no error. - Missing the guard. Without
bestIndex != -1, the first round with nobody left throwsArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1on a one-element list. - Sizing
usedfrom the original arrays. It would have six slots for three entries. The extra slots stayfalseand are never read, so the code may still seem to work, but the array doesn't match the lists it describes. Size it from the filtered lists. - Case and spelling.
"laptop"is not"Laptop", so the filter keeps nothing. - Ties. TechPro and AlphaTech both have 4, and the one listed first comes first. The strict
>in the comparison is what keeps that order. - Filtering one list only. If a rating is copied without its brand, the lists drift apart and the names no longer match the ratings. Both
addcalls belong to the sameif.
Testing
| target, k | output |
|---|---|
| Laptop, 2 | 1. NeoByte (5), 2. TechPro (4) |
| Phone, 2 | 1. MegaCorp (5), 2. Zenith (4) |
| Laptop, 3 | 1. NeoByte (5), 2. TechPro (4), 3. AlphaTech (4) |
| Laptop, 5 | the same three lines |
| Tablet, 3 | 1. Quantum (3) |
| Desktop, 2 | an empty line |
