encounter a strange behavior while trying to search for width with Go

Asked 2 years ago, Updated 2 years ago, 39 views

Easy go programming site
http://www.geocities.jp/m_hiroi/golang/puzgo01.html
I was learning width-first search in
If you use makePath but append,
Print [0 2 46 ] twice.
When I did print debugging, I queued the same thing several times.
I don't know why it's moving like that.
When I tried to substitute the slice beyond the original array part in append, I thought they were trying to make another array that copied the original array and refer to the array, but I think that's the mistake.
Please tell me why you defined makePath in the original and why my program failed.
The code is
https://play.golang.org/p/8s1-bf7qFd
I put it in the .

algorithm go

2022-09-29 21:58

1 Answers

append returns a copy when the array runs out of capacity.

package main

import "fmt"

funcmain(){
    a: = [ ] int {1,2,3,4}

    fmt.Println(cap(a))//=>4
    fmt.Println(cap(a[:3]))//=>4

    fmt.Println(append(a[:3],5))//=>[1235]
    fmt.Println(a)//=>[12 35]

    b: = append(a[:4], 5) // Insufficient capacity
    fmt.Println(append(b[:3],6))//=>[1 2 3 6]
    fmt.Println(a)//=>[12 35]
}

Also, the size and capacity of the slice after append do not always match.
If you try executing the code below, the capacity is 8, so you can still afford append without copying.

package main

import "fmt"

funcmain(){
    a: = [ ] int {1,2,3,4}
    b: = [ ] int {5,6}
    c:=append(a,b...)
    fmt.Println(len(c),cap(c))//=>68
}

Therefore, the questioner's code does not guarantee that the slice will be copied when append.

If you want to make sure you copy the slices, you can do append with an empty array.
In other words, makePath can be written shorter.

 func makePath(path[]int, xint)[]int{
    return append (append([]int(nil), path...), x)
}


2022-09-29 21:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.