Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding indices of max value in swift array

Tags:

arrays

swift

I have 2 arrays. One for players and one for scores. e.g.

var players = ["Bill", "Bob", "Sam", "Dave"]
var scores = [10,15,12,15]

I can find the index of the (first) max score (and the winner's name) by using:

let highScore = scores.max()
let winningPlayerIndex = scores.index(of: highScore!)
let winningPlayer = players[winningPlayerIndex!]

This works fine if there is only one player with the highest score but how would I return multiple indices (i.e. 1 and 3 in this example) for all values that are equal to the max value? I need the indices to then map back to the players array to pull out the names of all the players with the highest score. Or is there a better way to do all of this?

like image 855
mallowman Avatar asked May 05 '17 14:05

mallowman


1 Answers

The accepted answer doesn't generalize to comparing computed values on the elements. The simplest and most efficient way to get the min/max value and index is to enumerate the list and work with the tuples (offset, element) instead:

struct Player {
    let name: String
    let stats: [Double]
}

let found = players.enumerated().max(by: { (a, b) in
   battingAvg(a.element.stats) < battingAvg(b.element.stats)
})

print(found.element.name, found.offset)  // "Joe", 42

In general you shouldn't rely on comparing floating point values by equality and even where you can, if the computation is expensive you don't want to repeat it to find the item in the list.

like image 61
Pat Niemeyer Avatar answered Oct 11 '22 19:10

Pat Niemeyer