我读了我创建的随机文本文件
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
,其键为一致性,值为具有一致性的糖果成本之和。然后,你可以简单地找到通过简单地调用最昂贵的一致性类型max(by:)
上Dictionary
。
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
给定示例数组的值将为
[“软”:65,“硬”:50,“耐嚼”:35]
并且mostExpensiveConsistency
将
(键“软”,值65)`
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句