ADD: randstr

This commit is contained in:
NorthCityChen 2022-04-04 16:10:57 +08:00
parent 9b0c409a97
commit 2cb1a5c174
2 changed files with 61 additions and 7 deletions

28
app.go
View File

@ -1,6 +1,6 @@
/* /*
* @Author: NorthCity1984 * @Author: NorthCity1984
* @LastEditTime: 2022-04-03 09:31:39 * @LastEditTime: 2022-04-04 16:09:13
* @Description: * @Description:
* @Website: https://grimoire.cn * @Website: https://grimoire.cn
* Copyright (c) NorthCity1984 All rights reserved. * Copyright (c) NorthCity1984 All rights reserved.
@ -8,14 +8,28 @@
package main package main
import ( import (
// "githuh"
"fmt" "fmt"
"math"
"gitee.com/NorthCityChen/stl-go/randoom"
) )
func main() { func main() {
// ans := math.Exp2(0) // // ans := math.Exp2(0)
ans := math.Sqrt(-8) // ans := math.Sqrt(-8)
// ans2 := math1.Sqrt(-8) // // ans2 := math1.Sqrt(-8)
fmt.Println(ans) // fmt.Println(ans)
// fmt.Println(ans2) // // fmt.Println(ans2)
// string
// queue
// queue
// random.RandStringBytesMaskImprSrcSB(5)
// fmt.Println(r)
// ret := randoom.RandStr(45)
fmt.Println(randoom.RandStr(45))
fmt.Println(randoom.RandStr(45))
fmt.Println(randoom.RandStr(45))
fmt.Println(randoom.RandStr(45))
fmt.Println(randoom.RandStr(45))
} }

40
randoom/random.go Normal file
View File

@ -0,0 +1,40 @@
/*
* @Author: NorthCity1984
* @LastEditTime: 2022-04-04 16:10:11
* @Description:
* @Website: https://grimoire.cn
* Copyright (c) NorthCity1984 All rights reserved.
*/
package randoom
import (
"math/rand"
"strings"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
func RandStr(strLen int) string {
str := strings.Builder{}
str.Grow(strLen)
for i, cache, remain := strLen-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
str.WriteByte(letterBytes[idx])
i--
}
cache >>= letterIdxBits
remain--
}
return str.String()
}