diff --git a/README.md b/README.md index 2ba4a783..5b8b0fba 100644 --- a/README.md +++ b/README.md @@ -94,13 +94,15 @@ var ( separator = flag.String("separator", "-", "The separator between words in the pet name") ) -func init() { - rand.Seed(time.Now().UTC().UnixNano()) -} - func main() { flag.Parse() - rand.Seed(time.Now().UnixNano()) + + // To have a predictable series of petnames. (This is the default) + petname.Seed(1) + + // To have an unpredictable series of petnames. + petname.NonDeterministicMode() + fmt.Println(petname.Generate(*words, *separator)) } ``` diff --git a/cmd/petname/main.go b/cmd/petname/main.go index 5c3a50cb..d527340e 100644 --- a/cmd/petname/main.go +++ b/cmd/petname/main.go @@ -22,22 +22,18 @@ package main import ( "flag" "fmt" - "math/rand" "time" - "github.com/dustinkirkland/golang-petname" + + petname "github.com/dustinkirkland/golang-petname" ) var ( - words = flag.Int("words", 2, "The number of words in the pet name") + words = flag.Int("words", 2, "The number of words in the pet name") separator = flag.String("separator", "-", "The separator between words in the pet name") ) -func init() { - rand.Seed(time.Now().UTC().UnixNano()) -} - func main() { flag.Parse() - rand.Seed(time.Now().UnixNano()) + petname.Seed(time.Now().UnixNano()) fmt.Println(petname.Generate(*words, *separator)) } diff --git a/petname.go b/petname.go index d70fd693..552f218c 100644 --- a/petname.go +++ b/petname.go @@ -41,24 +41,36 @@ var ( // End word lists -// Call this function once before using any other to get real random results +var localRand *rand.Rand = rand.New(rand.NewSource(1)) + +// NonDeterministicMode configures the local random generator used internally +// to provide non deterministic results, instead of a pre-defined order that is +// reproducible even after a process restart. If you wish to specify a custom +// contant, call [Seed(int64)]. func NonDeterministicMode() { - rand.Seed(time.Now().UnixNano()) + localRand.Seed(time.Now().UnixNano()) +} + +// Seed configures the local random generator, allowing you to specify a +// constant for reproducible "randomness" or provide a custom value for +// "true" randomness. +func Seed(seed int64) { + localRand.Seed(seed) } // Adverb returns a random adverb from a list of petname adverbs. func Adverb() string { - return adverbs[rand.Intn(len(adverbs))] + return adverbs[localRand.Intn(len(adverbs))] } // Adjective returns a random adjective from a list of petname adjectives. func Adjective() string { - return adjectives[rand.Intn(len(adjectives))] + return adjectives[localRand.Intn(len(adjectives))] } // Name returns a random name from a list of petname names. func Name() string { - return names[rand.Intn(len(names))] + return names[localRand.Intn(len(names))] } // Generate generates and returns a random pet name.