快速数组中找到最大值的索引 [英] Finding indices of max value in swift array
问题描述
我有2个数组.一个给玩家,一个给分数.例如
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!]
如果只有一个得分最高的玩家,这很好用,但是对于等于最大值的所有值,我将如何返回多个索引(在本示例中为1和3)?我需要索引然后映射回玩家数组,以提取得分最高的所有玩家的姓名.还是有更好的方法来完成所有这些工作?
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?
推荐答案
您需要的是使用自定义 class
或 structure
并对其进行排列,然后找到最高分然后用最高分数过滤您的数组.
What you need is to use custom class
or structure
and make array of it then find max score and after that filter your array with max score.
struct Player {
let name: String
let score: Int
}
现在创建此Player 结构
Now create array of this Player structure
var players = [Player(name: "Bill", score: 10), Player(name: "Bob", score: 15), Player(name: "Sam", score: 12), Player(name: "Dave", score: 15)]
let maxScore = players.max(by: { $0.0.score < $0.1.score })?.score ?? 0
要获得具有最大核心数的播放器数组,请对此类数组使用过滤器.
To get the array of player with max core use filter on array like this.
let allPlayerWithMaxScore = players.filter { $0.score == maxScore }
要获得得分较高的玩家的索引数组,请对此类数组使用过滤器.
To get the array of index for player having high score use filter on array like this.
let indexForPlayerWithMaxScore = players.indices.filter { players[$0].score == maxScore }
print(indexForPlayerWithMaxScore) //[1, 3]
这篇关于快速数组中找到最大值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!