前兩天在解掃地機器人算法的問題時,遇到一個坑
部分代碼如下:
func move2(startPoint Point) [][]Point {
allFootPrint := [][]Point{{startPoint}}
for i := 0; i < N; i++ {
allNewFootPrint := make([][]Point, 0)
for len(allFootPrint) > 0 {
curFootPrint := allFootPrint[len(allFootPrint)-1]
allFootPrint = allFootPrint[:len(allFootPrint)-1]
last := curFootPrint[len(curFootPrint)-1]
for _, d := range directions {
nextPoint := Point{last.X + d[0], last.Y + d[1]}
if !inArray(nextPoint, curFootPrint) {
// 必須複製一份數據出來,否則會發生路徑重複
newCurFootPrint := make([]Point, len(curFootPrint))
copy(newCurFootPrint, curFootPrint)
allNewFootPrint = append(allNewFootPrint, append(newCurFootPrint, nextPoint))
}
}
}
allFootPrint = allNewFootPrint
}
return allFootPrint
}
這處註釋的地方非常關鍵,如果不複製出來,會導至allNewFootPrint中出現連續的兩個相同路徑,並且不是所有的路徑都出問題,只會在一輪循環結束後,新一輪循環開始時纔會出現,當時查了半天才查出問題。
現在把這個問題單獨拎出來,分享給大家。
package main
import "fmt"
func main() {
a := []int{1,2,3,4,5,6}
x := a[:2]
x = append(x, 9)
fmt.Println(x)
fmt.Println(a)
}
輸出:
[1 2 9]
[1 2 9 4 5 6]
上面的操作很簡單,就是從a切片裏取出前2個,然後再追加一個數字9進去。
結果我們發現x是正確的,但a切片也隨之發生了改動。
這說明x其實只是a切片的一個引用,對x的任何改動,都會影響到a。
這簡直是挖了個天大的坑,機器人的問題也正是這裏的問題。
只能copy出一個新的slice方能解決這個問題
package main
import "fmt"
func main() {
a := []int{1,2,3,4,5,6}
c := make([]int, 2)
copy(c, a[:2])
c = append(c, 9)
fmt.Println(c)
fmt.Println(a)
}
輸出:
[1 2 9]
[1 2 3 4 5 6]