Home > database >  Golang permutations of numbers, recursion not working
Golang permutations of numbers, recursion not working

Time:01-02

Here is the code:

package main

import "fmt"

func anon(n []int, sl []int, result [][]int) {
    if len(n) == 0 {
        result = append(result, sl)
        fmt.Printf("result %v\n", result)
        return
    }
    for i , _ := range n {
        fmt.Printf(" n %v\n", n)
        sl = append(sl, n[i])
        ab := append(n[:i], n[i 1:]...)
        fmt.Printf("i %v ---ab %v, sl %v, result %v ---\n",i, ab,sl,result )

        anon(ab, sl , result)
    }
}

func permute(nums []int) [][]int {
    var sl1 = []int{}
    var result = [][]int{}
    anon(nums, sl1, result)
 return result
}

func main() {
  sl2 := []int{1,2}
  permute(sl2)
  
}

I am expecting 'result' as [[1,2], [2,1]]. However, when I look at the below output from the code run:

 n [1 2]
i 0 ---ab [2], sl [1], result [] ---
 n [2]
i 0 ---ab [], sl [1 2], result [] ---
result [[1 2]]

n [2 2]

i 1 ---ab [2], sl [1 2], result [] ---

 n [2]
i 0 ---ab [], sl [1 2 2], result [] ---
result [[1 2 2]]

I see for (in bold) i=1, I have ab[2], sl[1 2], result[] and n[2,2]. I am not able to get it working for Golang. Something similar works well with Python.

Thanks for answering.

CodePudding user response:

Check this complete sample, which can help you to understand better how to make a permutation with golang: https://go.dev/play/p/JKG_FtilQCz.

In Golang slices are pointers to arrays, and when you make append(n[:i], n[i 1:]...) you are adding a new value in variable n, so you are changing the initial sl2 value, that should be {1,2} but is transformed in {2,2} as you noted. Try not to append in n, instead append in ab or something else.

  • Related