我正在努力在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
}