49 lines
974 B
Go
49 lines
974 B
Go
|
package main
|
||
|
|
||
|
import "math/rand/v2"
|
||
|
|
||
|
func generatePassword(sets [][]int, passwordLength int) []int {
|
||
|
numSets := len(sets)
|
||
|
totalLength := 0
|
||
|
for _, set := range sets {
|
||
|
totalLength += len(set)
|
||
|
}
|
||
|
|
||
|
props := make([]float64, numSets)
|
||
|
for i := range props {
|
||
|
props[i] = float64(len(sets[i])) / float64(totalLength)
|
||
|
}
|
||
|
|
||
|
numChars := make([]int, numSets)
|
||
|
for i := range numChars {
|
||
|
numChars[i] = int(props[i] * float64(passwordLength))
|
||
|
if numChars[i] == 0 {
|
||
|
numChars[i] = 1
|
||
|
}
|
||
|
}
|
||
|
|
||
|
totalChars := 0
|
||
|
for _, n := range numChars {
|
||
|
totalChars += n
|
||
|
}
|
||
|
|
||
|
if totalChars < passwordLength {
|
||
|
numChars[0]++
|
||
|
} else if totalChars > passwordLength {
|
||
|
numChars[numSets-1]--
|
||
|
}
|
||
|
|
||
|
password := make([]int, 0, passwordLength)
|
||
|
for i, set := range sets {
|
||
|
for j := 0; j < numChars[i]; j++ {
|
||
|
password = append(password, set[rand.IntN(len(set))])
|
||
|
}
|
||
|
}
|
||
|
|
||
|
rand.Shuffle(len(password), func(i, j int) {
|
||
|
password[i], password[j] = password[j], password[i]
|
||
|
})
|
||
|
|
||
|
return password
|
||
|
}
|