我一直在做一个项目,要求我从一组(复数)数字中生成所有可能的特定长度的元组。为了做到这一点,我尝试实现Mathematica Tuples[]命令的一个版本,但发现它不能正确生成所有元组。
在经历了许多挫折之后,我发现当我的程序生成长度为4的元组时,它会添加重复的元素而不是新元素,这导致任何长度更长的元组都有问题。我上网查看是否有人有其他类似的问题,然后找到一些其他代码来完成同样的任务,并注意到我的解决方案与他们的相似。我不知道我错在哪里。
在经历了更多的挫折之后,我发现如果我把元素前置到列表中,一切都很好,只有追加才是问题所在。我试图找出我原来的代码有什么问题,但什么也没找到。
下面是我用来演示这个问题的代码。我绝不是一个专业的编码员,所以如果这不是完成这个任务的最惯用的方法,你必须原谅我。目前我在我的实际代码中使用tuplesByPrepend函数,它工作得很好,我真的只是希望了解tuplesByAppend函数出了什么问题。同样,在第三,第五,第八,我测试过的任何其他级别似乎都做得很好。我可以提供更多关于我的操作系统和构建的信息,如果需要的话。
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)
}
字符集
1条答案
按热度按时间mzmfm0qo1#
在某些情况下,下面的行不像您预期的那样工作:
字符集
这个例子演示了发生了什么:
型
要防止它共享底层数组,请将
next := append(u, v)
替换为以下代码:型
请参阅Go Slices: usage and internals了解更多信息。