Improve generator function

This commit is contained in:
Illya Marchenko 2024-03-29 10:07:54 +02:00
parent 05e148698a
commit 615d03cc09
Signed by: stuzer05
GPG Key ID: A6ABAAA9268F9F4F

@ -2,44 +2,22 @@ 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)
func generatePassword(sets [][]int, length int) []int {
password := make([]int, length)
// Ensure at least one character from each set
for i, charSet := range sets {
password[i] = charSet[rand.IntN(len(charSet))]
}
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))])
}
// Fill the remaining positions with characters from all sets
for i := range password[len(sets):] {
charSetIndex := rand.IntN(len(sets))
charSet := sets[charSetIndex]
password[len(sets)+i] = charSet[rand.IntN(len(charSet))]
}
// Shuffle
rand.Shuffle(len(password), func(i, j int) {
password[i], password[j] = password[j], password[i]
})