gpt4 book ai didi

arrays - 过滤数组并将元素加在一起

转载 作者:搜寻专家 更新时间:2023-11-01 05:48:25 24 4
gpt4 key购买 nike

我读入了我创建的随机文本文件

hard        toffee        10
hard toffee 20
...
chewy gum 40
soft marshmallow 20
hard toffee 30
soft marshmallow 40

我创建了一个糖果/糖果对象数组并像这样存储它:

var candyArray = [
Candy(consistency: "hard", type: "toffee", cost: 10),
...
Candy(consistency: "soft", type: "marshmellow", cost: 40)]

可以通过其属性访问每个对象:

print(\(candyArray[0].type))
// prints toffeee

我想遍历数组,如果一致性很难,我想 += 用于存储硬糖成本总和的变量的成本。我想对其他一致性做同样的事情,然后将它们进行比较,看看总结后哪个成本最高。任何帮助都将不胜感激。这是我到目前为止所拥有的:

struct Candy {
var consistency: String
var type: String
var cost: Double

init(consistency: String, type: String, cost: Double) {
self.consistency = consistency
self.type = type
self.cost = cost
}

}

var candyArray = [
Candy(consistency: "hard", type: "toffee", cost: 40),
Candy(consistency: "hard", type: "toffee", cost: 5),
Candy(consistency: "hard", type: "toffee", cost: 5),
Candy(consistency: "soft", type: "marshmallow", cost: 30),
Candy(consistency: "soft", type: "marshmallow", cost: 35),
Candy(consistency: "chewy", type: "gum", cost: 35)

]

print("\(candyArray[0].type)")

var x = 0
var largestValue = 0.0
var tempValue = 0.0

var currentConsistency = candyArray[x].consistency
var mostExpensiveConsistency = ""


while (x < candyArray.count){
if (currentConsistency == candyArray[x].consistency) {
tempValue += candyArray[x].cost
} else if (currentConsistency != candyArray[x].consistency) {
tempValue = 0
currentConsistency = candyArray[x].consistency
}

if (tempValue > largestValue) {
largestValue = tempValue
mostExpensiveConsistency = currentConsistency
}
x+=1
}

print(" largest value: \(largestValue) and most expensive consistency: \(mostExpensiveConsistency)")

当一致性类型没有像我提到的上述文本文件中那样排序时,代码不起作用。我正在考虑创建一个二维数组或字典,并将一致性存储为键并将总和存储为每个一致性的值,这样如果一致性再次出现,我可以将它添加到先前存储在数组/字典中的总和中。我希望我说得有道理。我只是想知道是否有更快的方法。

最佳答案

你可以使用Array.reduce(into:)创建一个Dictionary,它的键是一致性,值是糖果成本的总和一致性。然后,您只需在 Dictionary 上调用 max(by:) 即可简单地找到最昂贵的一致性类型。

let candiesByConsistency = candyArray.reduce(into: [String:Double](), { accumulatedResults, current in
accumulatedResults[current.consistency, default: 0] += current.cost
})

let mostExpensiveConsistency = candiesByConsistency.max(by: { $0.value < $1.value })

给定示例数组的 candiesByConsistency 的值将是

["soft": 65, "hard": 50, "chewy": 35]

mostExpensiveConsistency 将是

(key "soft", value 65)`

关于arrays - 过滤数组并将元素加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48994103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com