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
The main mistake I was making was to use a var named the same as my function:
combos += combos(array, k)
Which is why I was seeing an error on this line and the other line where my function was being called.
After fixing that the rest of the problems were easier to solve :)
In case it will help anyone here's my working function:
func combos(var array: Array, k: Int) -> Array> {
if k == 0 {
return [[]]
}
if array.isEmpty {
return []
}
let head = array[0]
var ret: Array> = []
var subcombos = combos(array, k - 1)
for subcombo in subcombos {
var sub = subcombo
sub.insert(head, atIndex: 0)
ret.append(sub)
}
array.removeAtIndex(0)
ret += combos(array, k)
return ret
}
If anyone can improve it I'd be happy
For example can anyone explain how to get rid of the line var sub = subcombo
. i.e. how do I make subcombo
mutable by default?