Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick a random value from a Go Slice

Tags:

slice

random

go

Situation:

I've a slice of values and need to pick up a randomly chosen value from it. Then I want to concatenate it with a fixed string. This is my code so far:

func main() { //create the reasons slice and append reasons to it reasons := make([]string, 0) reasons = append(reasons,     "Locked out",     "Pipes broke",     "Food poisoning",     "Not feeling well")  message := fmt.Sprint("Gonna work from home...", pick a random reason ) } 

Question:

Is there a built-in function, which can help me by doing the "pick a random reason" part?

like image 503
Amistad Avatar asked Nov 30 '15 08:11

Amistad


People also ask

How do you generate a random number in Golang?

Golang has built-in support for random number generation in the standard library. Specifically there is the math/rand package which implements pseudo-random number generators. Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source.

How do I randomly select a string from a list?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you randomly pick an item from a slice?

The most naive approach is to randomly pick an item from your existing slice, remove it, and then insert it into a new slice. We can use the math/rand package’s Intn () method to pick the random element, and we can use append to remove elements from the middle of our slice.

How do you generate a random character from a slice?

Random element from slice To generate a character from an arbitrary set, choose a random index from a slice of characters: chars := []rune("AB⌘") c := chars[rand.Intn(len(chars))] // for example '⌘'

How to use intN (N) in the go playground to pick random elements?

The Go playground uses a fixed time so you will always get the same slice returned. Run it locally to see random shuffles. Intn (N) works by generating a random number between 0 and N (but not N) and then returning it. We can use this to pick a random element by using it to select a valid index and then getting the element at that index.

How do you pick a random letter from a string in go?

We pick a random letter by generating a random index of the string. We run the example three times. Go provides cryptographically secure pseudorandom number generator in the standard library package crypto/rand. While math/random is much faster, crypto/rand is suited for programs where security is paramount.


2 Answers

Use function Intn from rand package to select a random index.

import (   "math/rand"   "time" )  // ...  rand.Seed(time.Now().Unix()) // initialize global pseudo random generator message := fmt.Sprint("Gonna work from home...", reasons[rand.Intn(len(reasons))]) 

Other solution is to use Rand object.

s := rand.NewSource(time.Now().Unix()) r := rand.New(s) // initialize local pseudorandom generator  r.Intn(len(reasons)) 
like image 177
Grzegorz Żur Avatar answered Sep 19 '22 04:09

Grzegorz Żur


Just pick a random integer mod slice length:

rand.Seed(time.Now().Unix()) reasons := []string{     "Locked out",     "Pipes broke",     "Food poisoning",     "Not feeling well", } n := rand.Int() % len(reasons) fmt.Print("Gonna work from home...", reasons[n]) 

Playground: http://play.golang.org/p/fEHElLJrEZ. (Note the commend about rand.Seed.)

like image 22
Ainar-G Avatar answered Sep 21 '22 04:09

Ainar-G