[英]appending to slice of slices recursively
我正在嘗試在 Go 中實現一個簡單的函數,該函數返回一組數字的所有排列。 我讓它打印所有排列,但我無法將它們附加到 2D 切片。 這是排列的代碼:
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 時,它都會添加新切片並覆蓋所有其他切片。 為什么會這樣? 順便說一下,如果我只使用一個全局變量而不是一個指針也是一樣的。
謝謝
您不是將不同的[]int
切片附加到更大的[][]int
切片中,而是一遍又一遍地附加相同的 ( 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
更多信息。
好的,在@Amit Kumar Gupta 的幫助下,我開始工作了! 這是新代碼: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
}
這段代碼產生了這個答案:
[[1 2 3] [2 1 3] [3 1 2] [1 3 2] [2 3 1] [3 2 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.