Zana Daniel
Zana Daniel

Reputation: 301

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.

Upvotes: 1

Views: 141

Answers (2)

vacawama
vacawama

Reputation: 154583

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).

Upvotes: 3

Justin Doan
Justin Doan

Reputation: 166

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

Upvotes: -1

Related Questions