Home  >  Article  >  Backend Development  >  How to Generate All Possible n-Character Passwords in Go?

How to Generate All Possible n-Character Passwords in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-23 22:25:14334browse

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 1-character Cartesian product of {'a', 'b'} is {'a', 'b'}.
  • The 2-character Cartesian product is {('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')}.
  • The 3-character Cartesian product is {('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', '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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn