agoedken
agoedken

Reputation: 25

Generating a random variable in golang using math/rand

I'm trying to simulate a coin flip for a program in golang. I'm trying to use math/rand and I'm seeding it using time.

import (
"fmt"
"math/rand"
"time"
)    

From what I've looked up elsewhere on here and online, my implementation should work:

func main() {
    var random int
    var i int
    var j int
    for j != 5 && i != 5 {
        rand.Seed(time.Now().UnixNano())
        random = rand.Intn(1)
        if random == 0 {
            i = i + 1
        }
        if random == 1 {
            j = j + 1
        }
    }
fmt.Println(i, j)
}

But, each time I run it, random always end up being 0. The seed doesn't change either, which confuses me. Since it's within the loop, shouldn't the time in nanoseconds change each time it's seeded?

Upvotes: 1

Views: 2997

Answers (1)

Dave C
Dave C

Reputation: 7888

Don't reseed in the loop, do it only once.

rand.Intn(n) returns a value >= 0 and < n. So rand.Intn(1) can only return 0, you want rand.Intn(2) to get 0 or 1.

Fixed code: http://play.golang.org/p/3D9osMzRRb

Upvotes: 5

Related Questions