简体   繁体   中英

appending to slice of slices recursively

I am trying to implement a simple function in Go that returns all permutations of a set of numbers. I got it to print all of the permutations, but I cant get it to append those to a 2D slice. this is the code for the permutations:

package main

import "fmt"

// Generating permutation using Heap Algorithm
func heapPermutation(p *[][]int, a []int, size, n, count int) int {
    count++
    // if size becomes 1 then prints the obtained
    // permutation
    if size == 1 {
        fmt.Println(a)
        *p = append(*p, a)
        return count
    }
    i := 0
    for i < size {
        count = heapPermutation(p, a, size-1, n, count)

        // if size is odd, swap first and last
        // element
        // else If size is even, swap ith and last element
        if size%2 != 0 {
            a[0], a[size-1] = a[size-1], a[0]
        } else {
            a[i], a[size-1] = a[size-1], a[i]
        }
        i++
    }
    return count
}

and this is the main function:

func main() {
    listNumbers := []int{1, 2, 3}
    n := len(listNumbers)
    permutations := make([][]int, 0)
    p := &permutations
    heapPermutation(p, listNumbers, n, n, 0)
    fmt.Print(permutations)
}

when I run this code I get this output:

[1 2 3]
[2 1 3]
[3 1 2]
[1 3 2]
[2 3 1]
[3 2 1]
[[1 2 3] [1 2 3] [1 2 3] [1 2 3] [1 2 3] [1 2 3]]

So you can see that the function is able to find the permutations but something weird happens when I try to append it. If I add a fmt.Println(*p) before each append I get this result:

[1 2 3]
[[1 2 3]]
[2 1 3]
[[2 1 3] [2 1 3]]
[3 1 2]
[[3 1 2] [3 1 2] [3 1 2]]
[1 3 2]
[[1 3 2] [1 3 2] [1 3 2] [1 3 2]]
[2 3 1]
[[2 3 1] [2 3 1] [2 3 1] [2 3 1] [2 3 1]]
[3 2 1]
[[3 2 1] [3 2 1] [3 2 1] [3 2 1] [3 2 1] [3 2 1]]
[[1 2 3] [1 2 3] [1 2 3] [1 2 3] [1 2 3] [1 2 3]]

So it looks like every time I use append, it adds the new slice and overwrites all the other slices. Why does that happened? By the way, it's the same if I just use a global variable instead of a pointer.

Thanks

You're not appending different []int slices into the bigger [][]int slice, you're appending the same one ( a ) over and over again. And you're modifying a several times. By the end, you've modified a back to what it originally was, which is why your final output looks like the original input listNumbers repeated six times.

Here's a more straightforward way to see the problem:

package main

import "fmt"

func main() {
  a := []int{1}
  p := [][]int{a, a, a}
  fmt.Println(p) // [[1] [1] [1]]
  a[0] = 2
  fmt.Println(p) // [[2] [2] [2]]
}

To get your desired result, you need to make copies of a which don't get affected later when you subsequently modify a . Eg:

tmp := make([]int, len(a))
copy(tmp, a)
*p = append(*p, tmp)

Read more about copy here .

Ok so by the help of @Amit Kumar Gupta, I got it working! this is the new code: package main

    import "fmt"

    // Generating permutation using Heap Algorithm
    func heapPermutation(p *[][]int, a []int, size, n, count int) int {
        count++
        // if size becomes 1 then prints the obtained
        // permutation
        if size == 1 {
            fmt.Println(a)
            tmp := make([]int, len(a)) 
            /*
            'a' is like a pointer to an object,
            every time you modify 'a' it will change all the elemets of 'a'
            in the permutations list.
            like so
            :
            a := []int{1}
            p := [][]int{a, a, a}
            fmt.Println(p) // [[1] [1] [1]]
            a[0] = 2
            fmt.Println(p) // [[2] [2] [2]]
            */
            copy(tmp, a)
            *p = append(*p, tmp)
            fmt.Println(*p)
            return count
        }
        i := 0
        for i < size {
            count = heapPermutation(p, a, size-1, n, count)

            // if size is odd, swap first and last
            // element
            // else If size is even, swap ith and last element
            if size%2 != 0 {
                a[0], a[size-1] = a[size-1], a[0]
            } else {
                a[i], a[size-1] = a[size-1], a[i]
            }
            i++
        }
        return count
    }

this code produces this answer :

[[1 2 3] [2 1 3] [3 1 2] [1 3 2] [2 3 1] [3 2 1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM