I can't get what is going on on the following code in function findCombis. The outer scope variable out [][]int
looses its contents when data is appended, as shows the print out. Any suggestions why is this happening?
Thanks
package main
import "fmt"
func main() {
arr := []int{1, 3, 5, 7, 9}
comb := findCombis(arr, len(arr), 4)
fmt.Printf("%v
", comb)
}
func findCombis(arr []int, n int, m int) [][]int {
// define an array tthat will hold the arrays of combinations
out := [][]int{}
// define temporary array to hold currect combination
data := make([]int, m)
// define a func variable to use anonymous function with recursion
var combinationUtil func(arr []int, data []int, start, end, idx, m int)
// recursive function
combinationUtil = func(arr []int, data []int, start int, end int, idx int, m int) {
// current combination is ready store it
if idx == m {
fmt.Printf("DATA: %v
", data)
out = append(out, data)
fmt.Printf("OUT: %v
", out)
return
}
// replace index with all possible elements.
for i := start; i <= end && end-i+1 >= m-idx; i++ {
data[idx] = arr[i]
combinationUtil(arr, data, i+1, end, idx+1, m)
}
}
combinationUtil(arr, data, 0, n-1, 0, m)
return out
}