gpt4 book ai didi

Swift:分组配对,算法

转载 作者:行者123 更新时间:2023-11-30 12:36:29 24 4
gpt4 key购买 nike

我正在编写一种算法来将人们分组,目前,我可以为每组执行两个操作,前提是我想要分组的人数是偶数。

我需要帮助来优化算法以添加两个功能,

1)注意奇数,每个人都必须在一个组中

2)每组的人数应该是动态的,我可以决定配对 2、3、4 等

class Pair{

var key: String?
var value: String?

init(key: String, value: String) {
self.key = key
self.value = value
}
}



var pairList = [Pair]()

var names = ["Titi", "Bolu", "Tope", "Lola", "bolaji", "Idowu", "Philips", "Franka", "Dolphin", "Dolapo"]

//names.shuffle()

var counter = 0
for f in stride(from: 1, through: names.count, by: 2) {

var pair = Pair(key: names[counter], value: names[counter+1])
pairList.append(pair)
counter = counter + 2
}

names.removeAll()

for par in pairList{
print("\(par.key)" + " and " + "\(par.value)")
}

最佳答案

来自 @Alexander 分享的链接,这就是有效的方法 Mysterious "extra argument in call" error in Array extension method

extension Array {
func chunked(by chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0 ..< Swift.min($0 + chunkSize, self.count)]) // fixed
}
}
}

关于Swift:分组配对,算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42798288/

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