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

View File

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