英文:
Golang permutations of numbers, recursion not working
问题
这是代码:
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)
}
我期望的结果是result
为[[1,2], [2,1]]。然而,当我看到代码运行的输出如下所示时:
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=1时,ab为[2],sl为[1 2],result为空,n为[2,2]。我无法使其在Golang中正常工作。类似的代码在Python中可以正常工作。
谢谢回答。
英文:
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.
答案1
得分: 3
请查看这个完整的示例,它可以帮助你更好地理解如何使用golang
进行排列:https://go.dev/play/p/JKG_FtilQCz。
在Golang中,切片是指向数组的指针,当你使用append(n[:i], n[i+1:]...)
时,你在变量n
中添加了一个新值,因此你改变了初始的sl2
值,它应该是{1,2},但变成了{2,2},正如你所指出的。尝试不要在n
中添加,而是在ab
或其他地方添加。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论