Created
July 30, 2015 18:38
-
-
Save DAddYE/7d32ea0d950805c7f5f4 to your computer and use it in GitHub Desktop.
Generate pseudo random numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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