什么是为找出给定长度的所有可能的字的好方法 [英] What's a good way for figuring out all possible words of a given length
本文介绍了什么是为找出给定长度的所有可能的字的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个算法在C#中产生以下输出字符串:
AAAA
AAAB
AAAC
...等等...
ZZZX
ZZZY
ZZZZ
什么是实现这一目标的最佳方式是什么?
公共静态的IEnumerable<字符串> GetWords()
{
//执行算法
得到反馈字;
}
解决方案
好,如果长度为常数4,那么这将处理它:
公共静态的IEnumerable<字符串> GetWords()
{
对于(字符C1 ='A'; C1< ='Z'; C1 ++)
{
对于(字符C2 ='A'; C2< ='Z'; C2 ++)
{
对于(字符C3 ='A'; C3< ='Z'; C3 ++)
{
对于(字符C4 ='A'; C4< ='Z'; C4 ++)
{
得到回报+ C1 + C2 + C3 + C4;
}
}
}
}
}
如果长度为参数,这种递归的解决办法处理它:
公共静态的IEnumerable<字符串> GetWords(的Int32长度)
{
如果(长度&所述; = 0)
产生中断;
对于(字符C ='A';℃下='Z',C ++)
{
如果(长度大于1)
{
的foreach(字符串restWord在GetWords(长度 - 1))
产生收益C + restWord;
}
其他
收益回报+ C;
}
}
I'm trying to create an algorithm in C# which produces the following output strings:
AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ
What is the best way to accomplish this?
public static IEnumerable<string> GetWords()
{
//Perform algorithm
yield return word;
}
解决方案
well, if the length is a constant 4, then this would handle it:
public static IEnumerable<String> GetWords()
{
for (Char c1 = 'A'; c1 <= 'Z'; c1++)
{
for (Char c2 = 'A'; c2 <= 'Z'; c2++)
{
for (Char c3 = 'A'; c3 <= 'Z'; c3++)
{
for (Char c4 = 'A'; c4 <= 'Z'; c4++)
{
yield return "" + c1 + c2 + c3 + c4;
}
}
}
}
}
if the length is a parameter, this recursive solution would handle it:
public static IEnumerable<String> GetWords(Int32 length)
{
if (length <= 0)
yield break;
for (Char c = 'A'; c <= 'Z'; c++)
{
if (length > 1)
{
foreach (String restWord in GetWords(length - 1))
yield return c + restWord;
}
else
yield return "" + c;
}
}
这篇关于什么是为找出给定长度的所有可能的字的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文