Package math/rand provides support for generating pseudo-random numbers.
Here is how to generate a random integer between 0
and 99
:
n := rand.Intn(100) // n is a random int, 0 <= n < 100
Function rand.Float64
returns a random floating point number between 0.0
and 1.0
:
f := rand.Float64() // f is a random float64, 0.0 <= f < 1.0
There is also support for shuffling a slice (or other data structures):
x := []string{"a", "b", "c", "d", "e"}
// shuffling the slice put its elements into a random order
rand.Shuffle(len(x), func(i, j int) {
x[i], x[j] = x[j], x[i]
})
The number sequences generated by package math/rand
are not truly random.
Given a specific "seed" value, the results are entirely deterministic.
In Go 1.20+ the seed is automatically picked at random so you will see a different sequence of random numbers each time you run your program.
In prior versions of Go, the seed was 1
by default.
So to get different sequences for various runs of the program, you had to manually seed the random number generator, e.g. with the current time, before retrieving any random numbers.
rand.Seed(time.Now().UnixNano())
Elaine is working on a new children's game that features animals and magic wands. It is time to code functions for rolling a die, generating random wand energy and shuffling a slice.
Implement a RollADie
function.
This will be the traditional twenty-sided die with numbers 1 to 20.
d := RollADie() // d will be assigned a random int, 1 <= d <= 20
Implement a GenerateWandEnergy
function.
The wand energy should be a random floating point number equal or greater than 0.0 and less than 12.0.
f := GenerateWandEnergy() // f will be assigned a random float64, 0.0 <= f < 12.0
The game features eight different animals:
Write a function ShuffleAnimals
that returns a slice with the eight animals in random order.
Sign up to Exercism to learn and master Go with 34 concepts, 141 exercises, and real human mentoring, all for free.