I have a recursion code that adds a combination of numbers as a list in an output list.
The elements are appended correctly but the addition of a new list is changing the existing list in the output list.
Code:
func main() {
lst := []int{}
resampleCombination := [][]int{}
values := []int{1, 2, 3, 4}
n := len(values)
resampleCombination = f(lst, values, 0, n, resampleCombination)
fmt.Println(resampleCombination)
}
func f(lst, values []int, index, n int, rc [][]int) [][]int {
if index >= n {
if len(lst) > 2 {
rc = append(rc, lst)
fmt.Println("RC at time of append: ", rc)
}
return rc
}
lst = append(lst, values[index])
rc = f(lst, values, index+1, n, rc)
lst = lst[:len(lst)-1]
rc = f(lst, values, index+1, n, rc)
return rc
}
The output on the console:
RC at time of append: [[1 2 3 4]]
RC at time of append: [[1 2 3 4] [1 2 3]]
RC at time of append: [[1 2 4 4] [1 2 4] [1 2 4]]
RC at time of append: [[1 2 4 4] [1 2 4] [1 2 4] [1 3 4]]
RC at time of append: [[1 2 4 4] [1 2 4] [1 2 4] [1 3 4] [2 3 4]]
[[1 2 4 4] [1 2 4] [1 2 4] [1 3 4] [2 3 4]]
The first element appended to the output list was [1 2 3 4]
but as a new list [1,2,4]
is created, it changed to [1 2 4 4]
I know how to fix this. If we add the following code:
if index >= n {
if len(lst) > 2 {
listCopy := make([]int, len(lst))
copy(listCopy, lst)
rc = append(rc, listCopy)
My question is why is there a need to copy the list?
How and why the first list [1,2,3,4]
is changed to [1,2,4,4]
when [1,2,4]
is created?
If you do fmt.Println()
before and after lst = append(lst, values[index])
, you will find that after the append line is executed, the output list changes.
Code:
fmt.Println("rc before append line: ", rc)
lst = append(lst, prices[index])
fmt.Println("rc after append line: ", rc)
Output:
...
RC at time of append: [[1 2 3 4] [1 2 3]]
rc before append line: [[1 2 3 4] [1 2 3]]
rc after append line: [[1 2 4 4] [1 2 4]]
RC at time of append: [[1 2 4 4] [1 2 4] [1 2 4]]
...
Also, for your understanding, here is the flow of the recursion: