Skip to content

Latest commit

 

History

History
112 lines (75 loc) · 2.91 KB

README.md

File metadata and controls

112 lines (75 loc) · 2.91 KB

Animal Magic

Welcome to Animal Magic on Exercism's Go Track. If you need help running the tests or submitting your code, check out HELP.md. If you get stuck on the exercise, check out HINTS.md, but try and solve it without using those first :)

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.
They are completely determined by an initial seed value. By default, the package uses the integer 1 as a seed.

In order to get a different sequence of random numbers, we need to specify a different seed value. A simple approach is to use the "current time":

rand.Seed(time.Now().UnixNano())

Setting the seed must be done before calling any of the functions that generate random numbers. We usually only need to set the seed once in our program. From one seed we can generate many random numbers.

Warning

If you don't call rand.Seed, then the package will produce the same sequence of random numbers each time your program runs!

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. Seed the random number generator.

Implement a SeedWithTime function that seeds the math.rand package with the current computer time.

2. 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

3. 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

4. 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.

Source

Created by

  • @norbs57

My Solution