I try to generate a random 4-chars HEX string with the following code. Theoretically, the combination should be 2^4*2^4*2^4*2^4 = 2^16 but there are couples of collisions in 1000 rounds. Would like to know if the random seed is not spread evenly or any other possibilities?
package main
import(
"fmt"
"math/rand"
"time"
)
const letterBytes = "abcdef0123456789"
const testRun = 1000
const tokenLength = 4
func main(){
rs := make(map[string]int, testRun)
for i := 0 ; i < testRun ; i++ {
k := RandStringBytes(tokenLength)
_, ok := rs[k]
if ok {
fmt.Printf("collision key:%s on round:%d and %d \n", k, i, rs[k])
}
rs[k] = i
time.Sleep(5 * time.Millisecond)
}
}
func RandStringBytes(n int) string {
rand := *rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
Result: Try on Go playground
collision key:9536 on round:664 and 328
collision key:a313 on round:685 and 382
collision key:2ba6 on round:742 and 91
collision key:fe63 on round:937 and 146
collision key:0391 on round:962 and 226
Aucun commentaire:
Enregistrer un commentaire