gpt4 book ai didi

pointers - 递归地附加到 slice

转载 作者:行者123 更新时间:2023-12-01 22:15:01 25 4
gpt4 key购买 nike

我试图在Go中实现一个简单的函数,该函数返回一组数字的所有排列。我可以打印所有排列,但是无法将它们附加到2D slice 上。
这是排列的代码:

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
}

这是主要功能:

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)
}

当我运行此代码时,我得到以下输出:
[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]]

因此,您可以看到该函数能够找到排列,但是当我尝试附加该排列时会发生一些奇怪的事情。如果我在每次追加之前添加 fmt.Println(*p),则会得到以下结果:
[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]]

因此,看起来每次我使用append时,它都会添加新的 slice 并覆盖所有其他 slice 。为什么会这样呢?顺便说一句,如果我只是使用全局变量而不是指针,则是相同的。

谢谢

最佳答案

您没有在更大的[]int slice 中附加不同的[][]int slice ,而是一次又一次地添加了相同的a。并且您要多次修改a。最后,您已经将a修改回了原来的样子,这就是为什么最终输出看起来像原始输入listNumbers重复了六次的原因。

这是解决问题的更直接的方法:

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]]
}

为了获得所需的结果,您需要制作 a的副本,以后再修改 a时该副本不会受到影响。例如。:

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

阅读有关 copy here的更多信息。

关于pointers - 递归地附加到 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com