Skip to content

Instantly share code, notes, and snippets.

@DAddYE
Created July 30, 2015 18:38
Show Gist options
  • Save DAddYE/7d32ea0d950805c7f5f4 to your computer and use it in GitHub Desktop.
Save DAddYE/7d32ea0d950805c7f5f4 to your computer and use it in GitHub Desktop.
Generate pseudo random numbers
package main
import (
"crypto/rand"
"math/big"
)
var maxID = new(big.Int).SetUint64(^uint64(0))
func genRandomID() uint64 {
id, err := rand.Int(rand.Reader, maxID)
if err != nil { // this should never happen
panic(err)
}
return id.Uint64()
}
// TEST
package main
import "testing"
func TestGenRandomID(t *testing.T) {
const max = 1e6 // 1M
seen := make(map[uint64]struct{})
for i := 0; i < max; i++ {
id := genRandomID()
if _, found := seen[id]; found {
t.Fatalf("id %d not unique", id)
}
seen[id] = struct{}{}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment