Skip to content

Latest commit

 

History

History
84 lines (57 loc) · 2.28 KB

goRandom.md

File metadata and controls

84 lines (57 loc) · 2.28 KB

Introduction

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]
})

Seeds

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())

Learn More

Go by Example: random numbers Yourbasic.org: generate random numbers

Exercice Instructions

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.

1. Roll a die.

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

2. Generate wand energy.

Implement a GenerateWandEnergy function. The wand energy should be a random floating point number between 0.0 and 12.0.

f := GenerateWandEnergy()  // f will be assigned a random float64, 0.0 <= f < 12.0

3. Shuffle a slice.

The game features eight different animals:

  • ant
  • beaver
  • cat
  • dog
  • elephant
  • fox
  • giraffe
  • hedgehog

Write a function ShuffleAnimals that returns a slice with the eight animals in random order.