This is the code I'm working with:
package main
import "fmt"
import "math/rand"
func main() {
code := rand.Intn(900000)
fmt.Println(code)
}
It always returns 698081
. I don't understand, what the is problem?
https://play.golang.org/p/XisNbqCZls
Edit:
I tried rand.Seed
package main
import "fmt"
import "time"
import "math/rand"
func main() {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(900000)
fmt.Println(code)
}
There is no change. Now it always returns 452000
https://play.golang.org/p/E_Wfm5tOdH
https://play.golang.org/p/aVWIN1Eb84
In Golang, the rand. Seed() function is used to set a seed value to generate pseudo-random numbers. If the same seed value is used in every execution, then the same set of pseudo-random numbers is generated. In order to get a different set of pseudo-random numbers, we need to update the seed value.
Use Math. random() and Math. floor() method to get the random values. Push the values one by one in the array (But this approach may generate repeated values).
A couple of reasons why you'll see the same result in the playground
Last but not least, the rand
package default seed is 1
which will make the result deterministic. If you place a rand.Seed(time.Now().UnixNano())
you'll receive different results at each execution. Note that this won't work on the playground for the second reason above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With