Last active
June 7, 2024 06:31
-
-
Save bagasdisini/eb0b67352b93cb739795101a08926bf0 to your computer and use it in GitHub Desktop.
Randomize string with the most efficient way
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
func RandomString(n int) string { | |
src := rand.NewSource(time.Now().UnixNano()) | |
const str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
var letterIdxBits int64 = 6 | |
var letterIdxMask int64 = 1<<letterIdxBits - 1 | |
letterIdxMax := 63 / letterIdxBits | |
b := make([]byte, n) | |
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { | |
if remain == 0 { | |
cache, remain = src.Int63(), letterIdxMax | |
} | |
if idx := int(cache & letterIdxMask); idx < len(str) { | |
b[i] = str[idx] | |
i-- | |
} | |
cache >>= letterIdxBits | |
remain-- | |
} | |
return *(*string)(unsafe.Pointer(&b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source : stackoverflow