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
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
}