c# - 使用通配符生成单词的所有排列

标签 c# wildcard permutation combinations

我需要恢复我的密码,我知道一些字母,但忘记了其余部分使用的是什么字符。给定一些已知字符和一些未知字符,我需要一种方法来生成所有可能的密码排列。例如,我想在文本框中输入像“mic??s??t”这样的短语,程序会生成所有可能的排列组合。在这种情况下,我知道可能只使用几个字符来代替那些问号,但我希望程序可以选择排列所有字符 A-Z、a-z、0-9、/symbols/等,或者特定的字符集,如 E-G、t-y、1-4 等,通过第二个文本框作为字符串输入。

使用所有字符,它可能会生成一个列表

麦克风AAAT

云母

云母

麦克风AAADT

....

仅使用一组有限的字符,例如 E-G 看起来像

鼠标器

鼠标器

小鼠SEGt

小鼠场效应管

小鼠实验

....

如果做到这一点的唯一方法是为一个 N 长度的单词生成每个排列周期,无论通配符与否,然后使用正则表达式模式检查每个排列周期以过滤掉无用的,我可以接受(它会虽然生成 256^N 种可能的组合)。否则,我宁愿能够仅使用递归(我需要帮助)生成所有可能的数组。最后,我想生成这些排列的 txt 文件列表。我真的需要这里的递归帮助。我使用 C#。

最佳答案

这是一个混合了递归和迭代方法的简单解决方案。我想可以实现完全递归的解决方案,但我发现这种方法更容易理解。

//List of characters to substitute in place of '?'
List<char> validChars = new List<char>() { 'w', 'x', 'y', 'z' };
//List of combinations generated
List<string> combos = new List<string>();

void GenerateCombos(string mask, string combination)
{
    if (mask.Length <= 0)
    {
        //No more chars left in the mask, add this combination to the solution list.
        combos.Add(combination);
        return;
    }

    if (mask[0] != '?')
    {
        //This is not a wildcard, append the first character of the mask
        //to the combination string and call the function again with 
        //the remaining x characters of the mask.
        GenerateCombos(mask.Substring(1), combination + mask[0]);
    }
    else
    {
        //This is a wildcard, so for each of the valid substitution chars,
        //append the char to the combination string and call again
        //with the remaining x chars of the mask.
        validChars.ForEach(c => GenerateCombos(mask.Substring(1), combination + c));
    }
}

对该函数的调用将是:

string mask = "mic??s??t";
string combination = String.Empty;

GenerateCombos(mask, combination);

关于c# - 使用通配符生成单词的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8843977/

相关文章:

c# - T 类型的泛型,其中 T 具有特定属性

c# - 将 linq 中的 select 子句组合到具有匿名类型的实体

mysql - SQL 修剪通配符模式

java - Java 上的通配符和子类型

c# - 将 Linq 查询结果转换为接口(interface)

makefile 模式规则 : single wildcard, 先决条件中的多个实例

sql - 在 SQL Server 中生成排列的最优雅方式

matlab - Matlab 中集合的所有可能组合

python - 如何在C++中使用STL在低于总长度的位数下创建排列

c# - CLR 如何解析涉及动态类型的方法?