This recusion is adapted from http://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/ and does indeed print out all possible unique combination of arr
with length r
.
What I want from it is to save all possible combination in a list to further use this algorithm in another program. Why is the values overritten in combArray
in the recustion and how do I solve this?
def combRecursive(arr, data, start, end, index, r, combArray):
if index == r:
combArray.append(data)
return combArray
i = start
while True:
if i > end or end - i + 1 < r - index:
break
data[index] = arr[i]
combArray = combRecursive(arr, data, i + 1, end, index + 1, r, combArray)
i += 1
return combArray
def main():
arr = [1, 2, 3, 4, 5]
r = 3
n = len(arr)
data = [9999999, 9999999, 9999999]
combArray = []
combArray = combRecursive(arr, data, 0, n-1, 0, r, combArray)
print("All possible unique combination is: ")
for element in combArray:
print(element)
Result as of now:
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
[3, 4, 5]
What I want:
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]