在Swift中推广递归/循环

时间:2015-09-17 00:45:42

标签: ios algorithm swift

我正在努力在Swift中概括这个示例代码:

python manage.py migrate

目的是按顺序获得包含一个a字,一个b字和一个c字的所有组合。但我希望能够将其概括为任何序列(即acb,acdqp等)

理想情况下,我想传递一个字符串,如" acd"进入一个函数,返回一个匹配的句子数组。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我想出了一个解决方案。在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
}