简体   繁体   中英

How can I find the highest elements of an Array in Swift?

Can someone please explain how one would get the highest elements of an array in Swift 2.2?

For example lets say I have this code:

let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]

How would i retrieve the 3 highest values of that array? In this case I'd want the numbers 6, 7 and 11.

Any help would be greatly appreciated.

To find the 3 highest items, sort the array and take the last 3 items using suffix :

let myArray = [2, 1, 6, 3, 5 ,7, 11]
let highest3 = myArray.sort().suffix(3)
print(highest3)  // [6, 7, 11]

For the 3 lowest items, use prefix :

let lowest3 = myArray.sort().prefix(3)
print(lowest3)  // [1, 2, 3]

prefix and suffix have the added advantage that they do not crash if your array has fewer than 3 items. An array with 2 items for instance would just return those two items if you asked for .suffix(3) .

let highestNumber = myArray.maxElement()

Shown in playground

Edit: Sorry, didn't read the full question, this method only retrieves the one highest value, here is a reconfigured version that should work

let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11, 4, 12, 5]
var myArray2 = myArray
var highestNumbers: [Int] = []

while highestNumbers.count < 3 {
    highestNumbers.append(myArray2.maxElement()!)
    myArray2.removeAtIndex(myArray2.indexOf(myArray2.maxElement()!)!)
    print(highestNumbers)
}

Shown again in playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM