Apple Swift - Generate combinations with repetition

后端 未结 5 1941
自闭症患者
自闭症患者 2020-12-28 09:25

I\'m trying to generate a nested array containing all combinations with repetition in Apple\'s Swift programming language.

An detailed explanation of combinations wi

5条回答
  •  旧时难觅i
    2020-12-28 10:02

    Updated @richgordonuk answer for Swift 4 which provides a non-repetitive combination:

    func combinations(source: [T], takenBy : Int) -> [[T]] {
        if(source.count == takenBy) {
            return [source]
        }
    
        if(source.isEmpty) {
            return []
        }
    
        if(takenBy == 0) {
            return []
        }
    
        if(takenBy == 1) {
            return source.map { [$0] }
        }
    
        var result : [[T]] = []
    
        let rest = Array(source.suffix(from: 1))
        let subCombos = combinations(source: rest, takenBy: takenBy - 1)
        result += subCombos.map { [source[0]] + $0 }
        result += combinations(source: rest, takenBy: takenBy)
        return result
    }
    

提交回复
热议问题