提问人:Theodore Reimer 提问时间:11/8/2023 更新时间:11/8/2023 访问量:45
为什么这些元组没有正确生成?
Why are these tuples not generated correctly?
问:
我一直在做一个项目,这个项目要求我从一组(复数)数字中生成特定长度的所有可能的元组。为此,我尝试实现 Mathematica Tuples[] 命令的一个版本,但发现它没有正确生成所有元组。
经过一番挫折,我发现当我的程序生成长度为 4 的元组时,它会添加重复项而不是新元素,从而导致任何更长长度的元组出现问题。我在网上查看是否有人有任何其他类似的问题,然后找到一些其他代码来完成相同的任务,并注意到我的解决方案与他们的解决方案相似。我说不出我哪里做错了。
在更加沮丧之后,我发现如果我将元素添加到列表中,一切都可以正常工作,只有附加才是问题所在。我试图弄清楚我的原始代码出了什么问题,但一无所获。
下面是我为演示该问题而编写的代码。我绝不是一个专业的程序员,所以如果这不是完成这项任务的最惯用方式,你必须原谅我。目前,我在实际代码中使用元组ByPrepend函数,它工作正常,我真的只是希望了解元组ByAppend函数出了什么问题。同样,在第三、第五、第八和我测试过的任何其他级别,它似乎都做得很好。如果需要,我可以提供有关我的操作系统和构建的更多信息。
package main
import "fmt"
func tuplesByAppend[T any](list []T, depth int) [][]T {
var l1 [][]T
var l2 [][]T
for _, v := range list {
l1 = append(l1, []T{v})
}
for i := 1; i < depth; i++ {
for _, u := range l1 {
for _, v := range list {
// Differs here
next := append(u, v)
// next is calculated properly, but added to l2 incorrectly at the fourth level only
// at the fifth level it functions properly
// fmt.Println(next)
l2 = append(l2, next)
// fmt.Println(l2)
// it appears that at the fourth level it is writing over the previous entries
// Printing here yields
// [[1 1 1 1]]
// [[1 1 1 2] [1 1 1 2]]
// [[1 1 1 3] [1 1 1 3] [1 1 1 3]]
// [[1 1 1 3] [1 1 1 3] [1 1 1 3] [1 1 2 1]]
// [[1 1 1 3] [1 1 1 3] [1 1 1 3] [1 1 2 2] [1 1 2 2]]
// and so on.
}
}
l1 = l2
l2 = [][]T{}
}
return l1
}
func tuplesByPrepend[T any](list []T, depth int) [][]T {
var l1 [][]T
var l2 [][]T
for _, v := range list {
l1 = append(l1, []T{v})
}
for i := 1; i < depth; i++ {
for _, u := range l1 {
for _, v := range list {
// Differs here
next := append([]T{v}, u...)
l2 = append(l2, next)
}
}
l1 = l2
l2 = [][]T{}
}
return l1
}
func main() {
ourlist := []int{1, 2, 3}
ourdepth := 4
appended := tuplesByAppend(ourlist, ourdepth)
prepended := tuplesByPrepend(ourlist, ourdepth)
// We should expect this slice to start [1 1 1 1] [1 1 1 2] [1 1 1 3] [1 1 2 1] ...
// In fact, it starts [1 1 1 3] [1 1 1 3] [1 1 1 3] [1 1 2 3]
fmt.Println(appended)
// This slice is as expected
fmt.Println(prepended)
}
答:
4赞
Zeke Lu
11/8/2023
#1
在某些情况下,以下行无法按预期工作:
next := append(u, v)
此示例演示了发生的情况:
package main
import "fmt"
func main() {
u := append([]int{1, 2}, 3)
// The length is 3 but the capacity is 4.
fmt.Printf("u %v\n len: %d\n cap: %d\n", u, len(u), cap(u))
// Since u has enough capacity for the new element "4",
// v1 will share the same underlying array.
v1 := append(u, 4)
fmt.Println("v1:", v1)
// As what happened to v1, v2 will share the same underlying array too.
// But the last element "4" in the underlying array is changed to "5".
v2 := append(u, 5)
fmt.Println("v2:", v2)
// Since v1 uses the same underlying array, it sees the change in the last step.
fmt.Println("v1:", v1)
}
若要防止它共享基础数组,请替换为以下代码:next := append(u, v)
next := make([]T, len(u)+1)
copy(next, u)
next[len(u)] = v
评论