ranking list

๐Ÿ‘‰ replit

// name and score
let dict = [                                // Dictionary<Key, Value>
    "Sam": 79, "Joe": 5, "Mary": 79,        // Key     = String
    "Tom": 5, "Alex": 82, "Nancy": 1        // Value   = Int
] 

// โญ๏ธ 1. sort it by value first
let sorted = dict.sorted { $0.value > $1.value }

var prev: Int?              // previous score
var currentRank = 0
var rankingList = [(name: String, score: Int, rank: Int)]()

// โญ๏ธ 2. give every element a rank
for (i, elem) in sorted.enumerated() {
    
    // if elem.value is not the same as previous score,
    // update previous score and current rank
    if prev == nil || elem.value != prev! {
        prev = elem.value
        currentRank = i + 1         // i is zero-based, rank is one-based
    }
    
    rankingList.append((elem.key, elem.value, currentRank))
}

print(rankingList)
/*
[
    (name: "Alex" , score: 82, rank: 1), 
    (name: "Sam"  , score: 79, rank: 2), 
    (name: "Mary" , score: 79, rank: 2),    // no 3rd place
    (name: "Joe"  , score:  5, rank: 4), 
    (name: "Tom"  , score:  5, rank: 4),    // no 5th place
    (name: "Nancy", score:  1, rank: 6)
]
*/

Last updated