Improve generator function
This commit is contained in:
		
							
								
								
									
										46
									
								
								generator.go
									
									
									
									
									
								
							
							
						
						
									
										46
									
								
								generator.go
									
									
									
									
									
								
							@@ -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]
 | 
			
		||||
	})
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user