Home > Article > Backend Development > How to Generate All Possible n-Character Passwords in Go?
Generating All Possible n-Character Passwords in Go
To generate all possible passwords of a specified length using characters from a given set in Go, the concept of n-ary Cartesian product needs to be employed. Essentially, this involves constructing a Cartesian product of a set with itself n times.
The approach is iterative. The n-1 Cartesian product is first constructed. Then, for each product and each element of the initial set, the element is added to the product. For example, consider the generation of all 3-character passwords using the characters 'a' and 'b':
The following Go function, NAryProduct, implements this iterative construction:
import ( "fmt" "strings" ) func NAryProduct(input string, n int) []string { if n <= 0 { return nil } prod := make([]string, len(input)) for i, char := range input { prod[i] = string(char) } for i := 1; i < n; i++ { next := make([]string, 0, len(input)*len(prod)) for _, word := range prod { for _, char := range input { next = append(next, word + string(char)) } } prod = next } return prod }
Example usage:
fmt.Println(NAryProduct("abc", 3)) // [aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc]
Note that the provided solution can be further optimized by avoiding recalculation of previously computed sets.
The above is the detailed content of How to Generate All Possible n-Character Passwords in Go?. For more information, please follow other related articles on the PHP Chinese website!