【问题标题】:How to generate passwords? [duplicate]如何生成密码? [复制]
【发布时间】:2010-12-05 13:18:30
【问题描述】:

可能重复:
Get all possible word combinations

我有一个字符串"abcdefgklmno0123456789"

我需要列举所有可能的组合,大小从 6 到 7 个字符不等。

aaaaaa aaaaab aaaaac ... 999999

【问题讨论】:

  • “我需要列举所有可能的组合” - 不,你不需要。如果您正在生成密码,则不会......更像是试图破解密码......
  • @Mitch Wheat,如果你想破解它们,你可以这样做。我认为肯定有一所学校将其设置为作业的一部分。
  • 很遗憾这些天没有人在他们的密码中使用“p”。 :(
  • 或者'p'之后的任何字符,或者'h','i','j'。
  • 我最喜欢的密​​码是'password123'

标签: c#


【解决方案1】:

你可以使用 Linq 来做到这一点:

string s = "abcdefgklmno0123456789";

var pwdWith6Chars =
            from a in s
            from b in s
            from c in s
            from d in s
            from e in s
            from f in s
            select new string(new[] { a, b, c, d, e, f });

var pwdWith7Chars =
            from a in s
            from b in s
            from c in s
            from d in s
            from e in s
            from f in s
            from g in s
            select new string(new[] { a, b, c, d, e, f, g });

var passwords = pwdWith6Chars.Concat(pwdWith7Chars).ToList();

【讨论】:

  • 它只是一个笛卡尔积......有一种方法可以概括它,请参阅this post
【解决方案2】:

请查看以下链接。

它会帮助你

http://www.codeproject.com/KB/recipes/Combinatorics.aspx

【讨论】:

    【解决方案3】:

    您可以使用递归来生成此列表。

    伪代码(更像 C):

    str = "abcdefgklmno0123456789"
    res = empty string of 6 letters
    results = list of string
    
    function go(level) {
      if (level == 6 or level == 7) {
        add "res" to "results" list
        if (level == 7) {
          return
        }
      }
      for(i=position; i<len(str); i++) {
        res[level] = str[i]
        go(level+1)
      }
    }
    

    然后,你只需调用 go(0)。

    您也可以使用 yield 运算符来创建迭代器,而不是使用结果列表。 迭代器具有节省内存的优势,因为您将产生每个组合而不是存储所有组合。

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 2013-02-10
      • 2012-08-14
      • 2019-05-10
      • 2010-12-09
      • 2021-10-20
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多