gpt4 book ai didi

ios - 在 Swift 中推广递归/循环

转载 作者:行者123 更新时间:2023-11-30 14:04:06 25 4
gpt4 key购买 nike

我正在努力在 Swift 中推广此示例代码:

let words = [ ant, apple, banana, bear, cucumber, cheese ]

... // some sorting code

var sentences = [String]()

for aWord in wordsThatStartWithA {
bWord in wordsThatStartWithB {
cWord in wordsThatStartWithC {
sentences.append("\(aWord) \(bWord) \(cWord)")
}
}
}

// sentences -> "ant banana cucumber", "apple banana cucumber", "ant bear cucumber", ...

目标是按顺序获得包含一个 a 词、一个 b 词和一个 c 词的所有组合。但我希望能够将其推广到任何序列(即 acb、acdqp 等)

理想情况下,我想将像“acd”这样的字符串传递到返回匹配句子数组的函数中。任何帮助将不胜感激!

最佳答案

我已经想出了一个解决方案。在 Template 结构内部:

func sentencesWithWords(words: [String]) -> [String] {

// Group vocabulary into set of template options
let optionsSets = template.map { descriptor in
return words.filter({ $0.matchesDescriptor(descriptor) })
}

// Iterate through options set
var sentences = [String]()
for options in optionsSets {

// Append each option to each existing sentence
var newSentences = [String]()
for option in options {
if sentences.count == 0 {
newSentences.append(option)
} else {
for sentence in sentences {
newSentences.append("\(sentence) \(option)")
}
}
}

sentences = newSentences
}

return sentences
}

关于ios - 在 Swift 中推广递归/循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620929/

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