How to rank elements of an integer array based on their sorted order in Swift

1 Answer

0 votes
/*
    How to rank elements of an integer array based on their sorted order in Swift
    -----------------------------------------------------------------------------

    Ranking rules:
    - Lowest value gets rank 1
    - Equal values share the same rank
    - Rank increases only when encountering a new unique value

    Steps:
    1. Print the original array
    2. Create a copy of the array
    3. Sort the copy
    4. Build a map (value → rank)
    5. Apply ranks back to the original order
*/

import Foundation

// ------------------------------------------------------------
// Function 1: Print the array
// ------------------------------------------------------------
func printArray(_ arr: [Int]) {
    print("Array: \(arr)")
}

// ------------------------------------------------------------
// Function 2: Create a copy of the array
// ------------------------------------------------------------
func copyArray(_ arr: [Int]) -> [Int] {
    return arr.map { $0 }   // explicit copy
}

// ------------------------------------------------------------
// Function 3: Sort the array copy
// ------------------------------------------------------------
func sortArray(_ arrCopy: inout [Int]) {
    arrCopy.sort()
}

// ------------------------------------------------------------
// Function 4: Build a map of value → rank
// ------------------------------------------------------------
func buildRankMap(_ sortedArr: [Int]) -> [Int: Int] {

    var map: [Int: Int] = [:]

    guard !sortedArr.isEmpty else { return map }

    var rank = 1
    var previous = sortedArr[0]

    map[previous] = rank

    for i in 1..<sortedArr.count {
        let current = sortedArr[i]

        if current != previous {
            rank += 1
        }

        map[current] = rank
        previous = current
    }

    return map
}

// ------------------------------------------------------------
// Function 5: Apply ranks to original array order
// ------------------------------------------------------------
func applyRanks(_ original: [Int], _ rankMap: [Int: Int]) -> [Int] {
    return original.map { rankMap[$0]! }
}

// ------------------------------------------------------------
// Main ranking function
// ------------------------------------------------------------
func rankArray(_ arr: [Int]) {

    printArray(arr)

    if arr.isEmpty { return }

    var arrCopy = copyArray(arr)
    sortArray(&arrCopy)

    let rankMap = buildRankMap(arrCopy)

    let ranked = applyRanks(arr, rankMap)

    print("Rank: \(ranked)")
}

// ------------------------------------------------------------
// MAIN PROGRAM
// ------------------------------------------------------------
let arr = [33, 99, 10, 25, 47, 11, 77]

rankArray(arr)



/*
run:

Array: [33, 99, 10, 25, 47, 11, 77]
Rank: [4, 7, 1, 3, 5, 2, 6]


*/

 



answered 1 day ago by avibootz

Related questions

...