这里有点奇怪。我的问题是,人们运行我的代码会得到和我一样的结果吗?如果你这样做了,是我的代码有问题(我通常是一个 python 程序员),还是 golang 中的错误?
系统信息:围棋版本(1.1.2)的Linux的x64(Fedora的19)
代码的背景信息:我正在做的是找到从三角形顶部到底部的最高成本路线,这是来自 project_euler 18 和 67
该bug:我设置了一个名为pathA变量,这是一个整数列表,加上新价值新的int从三角形如3,7,2追加8中应该等于3,2,7,8,但它确实!......直到我设置pathB。pathB被设置正确但是突然pathA是相同的值pathB。
tl;dr当我设置另一个变量时,一个变量被覆盖
我的代码如下:
package main
import (
"fmt"
)
func extendPaths(triangle, prePaths [][]int) [][]int {
nextLine := triangle[len(prePaths)]
fmt.Println("#####PrePaths: ", prePaths)
fmt.Println("#####nextLine: ", nextLine)
postPaths := [][]int{{}}
for i := 0; i < len(prePaths); i++ {
route := prePaths[i]
nextA := nextLine[i]
nextB := nextLine[i+1]
fmt.Println("Next A:", nextA, "Next B:", nextB, "\n")
pathA := append(route, nextA)
fmt.Println("pathA check#1:", pathA)
pathB := append(route, nextB)
fmt.Println("pathA check#2:", pathA, "\n")
postPaths = append(postPaths, pathA)
postPaths = append(postPaths, pathB)
}
postPaths = postPaths[1:]
prePaths = [][]int{postPaths[0]}
for i := 1; i < len(postPaths)-1; i += 2 {
if getSum(postPaths[i]) > getSum(postPaths[i+1]) {
prePaths = append(prePaths, postPaths[i])
} else {
prePaths = append(prePaths, postPaths[i+1])
}
}
prePaths = append(prePaths, postPaths[len(postPaths)-1])
return prePaths
}
func getSum(sumList []int) int {
total := 0
for i := 0; i < len(sumList); i++ {
total += sumList[i]
}
return total
}
func getPaths(triangle [][]int) {
prePaths := [][]int{{triangle[0][0]}}
for i := 0; i < len(triangle)-1; i++ {
prePaths = extendPaths(triangle, prePaths)
}
}
func main() {
triangle := [][]int{{3}, {7, 4}, {2, 4, 6}, {8, 5, 9, 3}}
getPaths(triangle)
}
万千封印
相关分类