Start learning free

LESSON 257 OF 292 · NESTED LOOPS

Top K Brands V6 in Swift: Ranking with a Review-Count Tie-Break

Practice Read the full explanation

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 = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
        let ratings = [4, 5, 5, 3, 4]
        let reviews = [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).
  • k is 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 print(...).

Start from v4: the same var used = Array(repeating: false, count: ratings.count) and var lines = [String](), 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 = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
        let ratings = [4, 5, 5, 3, 4]
        let reviews = [200, 150, 500, 100, 300]
        let k = 3

        var used = Array(repeating: false, count: ratings.count)
        var lines = [String]()
        for rank in 1...k {
            var bestIndex = -1
            for index in ratings.indices {
                if !used[index] {
                    if bestIndex == -1 {
                        bestIndex = index
                    } else if ratings[index] > ratings[bestIndex] {
                        bestIndex = index
                    } else if ratings[index] == ratings[bestIndex] && reviews[index] > reviews[bestIndex] {
                        bestIndex = index
                    }
                }
            }
            used[bestIndex] = true
            lines.append("\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]), \(reviews[bestIndex]))")
        }
        print(lines.joined(separator: "\n"))

STEP 1 OF 12
    Ctrl + Enter to check

    SWIFT · NESTED LOOPS

    Top K Brands V6 in Swift, explained

    Problem overview

    Three parallel arrays describe five brands: brands, ratings and reviews, where position i in each refers to the same brand. The program prints the top k brands, one per line, in the form rank. Brand (rating, reviews), starting at rank 1. The ranking has two criteria:

    • The higher rating wins.
    • If two ratings are equal, the brand with more reviews wins.
    • If rating and reviews are both equal, the brand listed first wins.

    With k = 3 on the starter data, NeoByte and MegaCorp share a rating of 5, and NeoByte has more reviews. Zenith and TechPro share a 4, and Zenith has more reviews. The output is:

    1. NeoByte (5, 500)
    2. MegaCorp (5, 150)
    3. Zenith (4, 300)
    

    In this version k is never larger than the number of brands, and there is no product filter: the search works on all the brands.

    Approach: the same repeated search, a richer comparison

    The search is the repeated one from the earlier ranking versions. Each round scans the brands that are not taken yet, keeps a bestIndex that starts at -1, marks the round's winner in a used array, and adds a line. Only the question "does this brand beat the current best?" changes.

    That question now has three cases, tested in order:

    1. Nothing is chosen yet (bestIndex == -1): this brand becomes the best, because it has nobody to beat.
    2. Its rating is higher than the best one's: it becomes the best, and the reviews don't matter at all.
    3. The ratings are equal and it has more reviews: it becomes the best.

    Writing them as an if / else if chain matters. A case runs only when the ones above it failed, so the review count is looked at only when the rating isn't strictly higher. There is no case for equal ratings with equal reviews, so the brand listed first stays, which is exactly the third rule. Every comparison uses strictly greater, and a brand never replaces one that matches it completely.

    The rounds on the starter data

    In round 1, TechPro (4, 200) is chosen first because nothing is chosen yet. MegaCorp (5, 150) has a higher rating and replaces it. NeoByte (5, 500) has an equal rating and more reviews, so it replaces MegaCorp. Quantum and Zenith don't beat it. NeoByte wins. In round 2 NeoByte is skipped, and MegaCorp wins for the same reasons. In round 3 only TechPro (4, 200), Quantum (3, 100) and Zenith (4, 300) are left, and Zenith has the same rating as TechPro with more reviews, so Zenith takes third place.

    Step by step

    1. Create used with one false per brand and lines as an empty [String].
    2. Loop over the ranks with for rank in 1...k, and start each round with var bestIndex = -1.
    3. Loop over the positions with for index in ratings.indices, and skip the brands that are taken with if !used[index].
    4. First case: if bestIndex == -1, set bestIndex = index.
    5. Second case, an else if: the rating is higher than the best one's, so the brand becomes the best.
    6. Third case, another else if: the ratings are equal and the review count is higher. Both parts must hold, so they are joined with &&.
    7. After the scan, mark the winner by setting used[bestIndex] to true.
    8. Add the line with the rank, the name, then the rating and the review count in parentheses, separated by a comma and a space.
    9. Print the lines joined with a newline.

    The solution in Swift

    let brands = ["TechPro", "MegaCorp", "NeoByte", "Quantum", "Zenith"]
    let ratings = [4, 5, 5, 3, 4]
    let reviews = [200, 150, 500, 100, 300]
    let k = 3
    
    var used = Array(repeating: false, count: ratings.count)
    var lines = [String]()
    for rank in 1...k {
        var bestIndex = -1
        for index in ratings.indices {
            if !used[index] {
                if bestIndex == -1 {
                    bestIndex = index
                } else if ratings[index] > ratings[bestIndex] {
                    bestIndex = index
                } else if ratings[index] == ratings[bestIndex] && reviews[index] > reviews[bestIndex] {
                    bestIndex = index
                }
            }
        }
        used[bestIndex] = true
        lines.append("\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]), \(reviews[bestIndex]))")
    }
    print(lines.joined(separator: "\n"))
    

    Swift specifics worth knowing:

    • The chain is evaluated top to bottom. Swift stops at the first condition that is true. The third condition reads ratings[bestIndex], which is safe because the first case already handled bestIndex == -1.
    • && needs both sides true. A brand with more reviews but a lower rating never reaches a replacement: the second case fails because its rating isn't higher, and the third fails because the ratings aren't equal.
    • Interpolation with several values. The line "\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]), \(reviews[bestIndex]))" mixes text, an Int and a String without any conversion. The literal comma and space between the two numbers are ordinary characters in the string.
    • 1...k and ratings.indices. 1...k includes k, and indices gives the positions 0..<5 of the array.

    Edge cases and common mistakes

    • Reviews can't beat rating. With brands A (rating 3, 900 reviews) and B (rating 4, 5 reviews), B ranks first. The order is 1. B (4, 5) then 2. A (3, 900).
    • Full ties. With three brands that all have a 4 and 10 reviews, the output keeps the listed order: A, B, C. Using >= for the reviews would reverse it.
    • Tie on rating only. With ratings [5, 5, 5] and reviews [10, 30, 20], the output is B (30 reviews), then C (20), then A (10).
    • Forgetting the equal-rating test. A condition that only checks reviews[index] > reviews[bestIndex] would let a lower-rated brand with many reviews win.
    • Not marking the winner. Without used[bestIndex] = true, every round returns NeoByte.

    Testing

    These outputs come from the solution on the starter arrays with other values of k.

    • k = 1 prints 1. NeoByte (5, 500).
    • k = 5 prints NeoByte (5, 500), MegaCorp (5, 150), Zenith (4, 300), TechPro (4, 200) and Quantum (3, 100), in that order.

    Change the arrays in the editor above and check each of the three rules.

    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free