generate random number in a given range



Total noob, teaching myself how to code.

I just spent an hour trying to figure out how to generate a random number from a given range using the go programming language(golang).

Here's the best that I've found so far...

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

func random(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

func main() {
    myrand := random(1, 6)
    fmt.Println(myrand)
}

func random defines how to create the random number.
rand.Seed ensures that the number that is generated is random(almost).
func main gives you that random number within any two positive numbers that you specify (in this case, 1 and 6).

3 comments:

  1. package main
    import(
    "fmt"
    "math/rand"
    "time"
    )

    func random(min, max int) int {
    return rand.Intn(max - min) + min
    }

    func main() {
    rand.Seed(time.Now().Unix())
    myrand := random(1, 6)
    fmt.Println(myrand)
    }

    rand.Seed gets reset when called so you call it usually once when the program starts. The above code will result in a different random number each time your random function is called.

    ReplyDelete
  2. This code is vulnerable to a time attack. Given knowledge of the seed, the output is deterministic. Bad idea.

    Someone could create their own program that will produce identical outputs to your program, allowing them to know your "random" number. Its fine if you are only using it for learning, but dont use it in production.

    If you are on linux, you could poll "/dev/random" or "/dev/urandom" and have that be your seed. Or better yet, use crypto/rand.

    Good luck and have fun!

    ReplyDelete