动态字符发生器;从字符集生成所有可能的字符串 [英] Dynamic character generator; Generate all possible strings from a character set

查看:171
本文介绍了动态字符发生器;从字符集生成所有可能的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个动态字符串生成器,它将从一个动态长度的字符集中生成所有可能的唯一字符串。

我可以很容易地使用这个

  //打印长度为3 
$的所有可能的字符串b $ b for allowedCharacters {
for allowedCharacters {
for c in allowedCharacters {
println(a + b + c)
}
}





$ b

但是,当我想使这个长度的动态,所以我可以调用 generate(length:5)我感到困惑。

我发现这个 Stackoverflow问题但接受的答案生成字符串1-maxLength长度,我想永远字符串maxLength。

解决方案

如上所述,使用递归。这是如何用C#完成的:

  static IEnumerable< string>生成(int length,char [] allowed_chars)
{
if(length == 1)
{
foreach(char c in allowed_chars)
yield return c。的ToString();
}
else
{
var sub_strings =生成(length - 1,allowed_chars);

foreach(char c中的allowed_chars)
{
foreach(sub_strings中的字符串子)
{
yield return c + sub;





private static void Main(string [] args)
{

string chars =abc;

列表< string> result = Generate(3,chars.ToCharArray())。ToList();






$ b请注意这个算法的运行时间和金额它返回的数据是指数随着长度增加,这意味着如果你有很大的长度,你应该期待代码花费很长时间,并返回大量的数据。


I want to make a dynamic string generator that will generate all possible unique strings from a character set with a dynamic length.

I can make this very easily using for loops but then its static and not dynamic length.

// Prints all possible strings with the length of 3

for a in allowedCharacters {
    for b in allowedCharacters {
        for c in allowedCharacters {
            println(a+b+c)
        }
    }
}

But when I want to make this dynamic of length so I can just call generate(length: 5) I get confused.

I found this Stackoverflow question But the accepted answer generates strings 1-maxLength length and I want maxLength on ever string.

解决方案

As noted above, use recursion. Here is how it can be done with C#:

static IEnumerable<string> Generate(int length, char[] allowed_chars)
{
    if (length == 1)
    {
        foreach (char c in allowed_chars)
            yield return c.ToString();
    }
    else
    {
        var sub_strings = Generate(length - 1, allowed_chars);

        foreach (char c in allowed_chars)
        {
            foreach (string sub in sub_strings)
            {
                yield return c + sub;
            }

        }
    }
}

private static void Main(string[] args)
{

    string chars = "abc";

    List<string> result = Generate(3, chars.ToCharArray()).ToList();

}

Please note that the run time of this algorithm and the amount of data it returns is exponential as the length increases which means that if you have large lengths, you should expect the code to take a long time and to return a huge amount of data.

这篇关于动态字符发生器;从字符集生成所有可能的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆