mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Not So Random as a go til.
This commit is contained in:
@@ -15,6 +15,10 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Stashing Untracked Files](git/stashing-untracked-files.md)
|
- [Stashing Untracked Files](git/stashing-untracked-files.md)
|
||||||
- [Verbose Commit Message](git/verbose-commit-message.md)
|
- [Verbose Commit Message](git/verbose-commit-message.md)
|
||||||
|
|
||||||
|
### go
|
||||||
|
|
||||||
|
- [Not So Random](go/not-so-random.md)
|
||||||
|
|
||||||
### rails
|
### rails
|
||||||
|
|
||||||
- [Attribute Was](rails/attribute-was.md)
|
- [Attribute Was](rails/attribute-was.md)
|
||||||
|
|||||||
46
go/not-so-random.md
Normal file
46
go/not-so-random.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
# Not So Random
|
||||||
|
|
||||||
|
Go's `rand` package makes it easy to generate all sorts of random numbers.
|
||||||
|
What they don't tell you though is that the default seed is `1`. So if you
|
||||||
|
write a program like so:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
import "math/rand"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
stuff := []string{
|
||||||
|
"one",
|
||||||
|
"two",
|
||||||
|
"three",
|
||||||
|
"four",
|
||||||
|
}
|
||||||
|
fmt.Println(stuff[rand.Intn(len(stuff))])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
and then run it, you will get output like:
|
||||||
|
|
||||||
|
```
|
||||||
|
three
|
||||||
|
```
|
||||||
|
|
||||||
|
and any subsequent runs of the program will continue to produce `three`. Not
|
||||||
|
exactly what we are looking for.
|
||||||
|
|
||||||
|
If you want your program to be a little less predictable, you will want to
|
||||||
|
seed it yourself, perhaps with the current time, instead of `1`. Try adding
|
||||||
|
the following to the beginning of the `main` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
rand.Seed( time.Now().UTC().UnixNano())
|
||||||
|
```
|
||||||
|
|
||||||
|
You'll also want to import the `time` package.
|
||||||
|
|
||||||
|
Things should *appear* to be a bit more random now.
|
||||||
|
|
||||||
|
source: [Jake Worth](https://twitter.com/jwworth) and
|
||||||
|
[Stackoverflow](http://stackoverflow.com/questions/12321133/golang-random-number-generator-how-to-seed-properly)
|
||||||
Reference in New Issue
Block a user