Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Random number always return 168

Tags:

go

I am a complete noob in regards to Go.

I am trying to make a an arbitrary function that returns two random numbers added together.

I have pasted my code below, and cannot figure out why it always returns 168!

package main

import(
    "fmt"
    "math/rand"
)

func add(x int, y int) int{
    return x + y
}

var a int = rand.Intn(100)
var b int = rand.Intn(100)

func main() {
    fmt.Println(add(a, b))
}
like image 696
Brian Douglas Avatar asked May 14 '15 22:05

Brian Douglas


1 Answers

You have to specify seed to get different numbers. It is outlined in documentation:

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. Use the Seed function to initialize the default Source if different behavior is required for each run.

And some reference about Seed

Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1).

And you can see an example in the go cookbook:

rand.Seed(time.Now().Unix())

So wrapping up, you will have something like this:

package main

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

func add(x int, y int) int{
    return x + y
}


func main() {
    rand.Seed(time.Now().Unix())
    var a int = rand.Intn(100)
    var b int = rand.Intn(100)
    fmt.Println(add(a, b))
}
like image 115
Salvador Dali Avatar answered Nov 06 '22 22:11

Salvador Dali