UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Given an array of integers arr, replace each element with its rank.

Forums > Swift

Given an array of integers arr, replace each element with its rank. The rank represents how large the element is. The rank has the following rules:

Rank is an integer starting from 1. The larger the element, the larger the rank. If two elements are equal, their rank must be the same. Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30] Output: [4,1,2,3] Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest. Example 2:

Input: arr = [100,100,100] Output: [1,1,1] Explanation: Same elements share the same rank.

3      

import Foundation

func rankArray(_ array: [Int]) -> [Int] {
    let sortedArray = Set(array).sorted()
    return array.map {
        sortedArray.firstIndex(of: $0)! + 1
    }
}

let arr = [40, 10, 20, 30]
print(rankArray(arr))
//prints [4, 1, 2, 3]

let arr2 = [100, 100, 100]
print(rankArray(arr2))
//prints [1, 1, 1]

let arr3 = [40, 10, 20, 30, 30, 10, 50, 70]
print(rankArray(arr3))
//prints [4, 1, 2, 3, 3, 1, 5, 6]

Edit: A little change to rankArray to account for the third example

4      

@roosterboy

Thank you so much😍

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.