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
You can get rid of var sub = subcombo
by writing the loop as
for subcombo in subcombos {
ret.append([head] + subcombo)
}
This can be further simplified using the map()
function:
func combos(var array: Array, k: Int) -> Array> {
if k == 0 {
return [[]]
}
if array.isEmpty {
return []
}
let head = [array[0]]
let subcombos = combos(array, k: k - 1)
var ret = subcombos.map {head + $0}
array.removeAtIndex(0)
ret += combos(array, k: k)
return ret
}
Update for Swift 4:
func combos(elements: ArraySlice, k: Int) -> [[T]] {
if k == 0 {
return [[]]
}
guard let first = elements.first else {
return []
}
let head = [first]
let subcombos = combos(elements: elements, k: k - 1)
var ret = subcombos.map { head + $0 }
ret += combos(elements: elements.dropFirst(), k: k)
return ret
}
func combos(elements: Array, k: Int) -> [[T]] {
return combos(elements: ArraySlice(elements), k: k)
}
Now array slices are passed to the recursive calls to avoid the creation of many temporary arrays.
Example:
print(combos(elements: [1, 2, 3], k: 2))
// [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]