I'm playing around go and was trying to create a simple way to roll 3 dice and get the individual results or the total and was confused by the result.
In the code below I thought I was producing a new Roll struct, which would include a new array of 4 random results. Everytime I run the program though the results are exactly the same no matter what I do as if it's using the same array over and over again.
Sorry for the basic question but what am I doing wrong?
https://play.golang.org/p/ueu8eLMxab
package main
import (
"fmt"
"math/rand"
)
type Roll struct {
result [4]int
} //
func NewRoll() *Roll {
roll := new(Roll)
for i := range roll.result {
roll.result[i] = rand.Intn(3)
}
return roll}
func (r *Roll) Result() [4]int {
return r.result
}
func (r *Roll) Total() int {
var t int
for i := range r.result {
t = t + r.result[i]
}
return t
}
func main() {
roll := NewRoll()
fmt.Println(roll.Result())
fmt.Println(roll.Total())
}
**评论:**
jy3:
SteazGaming:I think I read somewhere that there is no random in the go playground . This may be your problem.
garslo:Many of the playground's system details are just spoofed. You can read more about it in this blog post: "https://blog.golang.org/playground"
"Although all these things are supported today, the first version of the playground, launched in 2010, had none of them. The current time was fixed at 10 November 2009, time.Sleep had no effect, and most functions of the os and net packages were stubbed out to return an EINVALID error.
A year ago we implemented fake time in the playground, so that programs that sleep would behave correctly. A more recent update to the playground introduced a fake network stack and a fake file system, making the playground's tool chain similar to a normal Go tool chain. These facilities are described in the following sections."
ProvokedGaming:You need to seed the math/rand module. From math/rand: "Use the Seed function to initialize the default Source if different behavior is required for each run."
A simple way is to do
rand.Seed(time.Now().Unix())
in your main. Something in the chain (either math/rand or time) is limited in the playground, but run it locally and it gives different results each time.
gschier2:You need to have a seeded random number generator based on something such as UnixTime. The problem is, time.Now() in the go playground is fixed and not updating. You can see that it is set to (2009-11-10 23:00:00 +0000 UTC) by doing a fmt.Printf("%s\n", time.Now()) in the playground.
Check out the docs on random number generation. Specifically "Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run"
