我想用C#风格的语言编写类似里程表的方法,但不只是使用0-9表示字符,而是使用任何字符集.它或多或少会像蛮力的应用程序.
如果我传入一个从0到J的字符数组,并将长度设置为5,我想要的结果如00000,00001,00002 ...... HJJJJ,IJJJJJ,JJJJJ.
这是基地,请帮我扩展:
protected void Main()
{
char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
BruteForce(chars, 5);
}
private void BruteForce(char[] chars, int length)
{
// for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
// (when passed in length is 5)
// TODO: Implement code...
}
Run Code Online (Sandbox Code Playgroud)
这不是相当的副本"递归,而不是多回路"但它相当接近.如果这对您没有帮助,我会写一个解决方案.
编辑:这是一个非递归的解决方案.递归的一个稍微难以返回一个IEnumerable<string>
,但返回一个迭代器给了一个很好的接口IMO :)
private static IEnumerable<string> GetAllMatches(char[] chars, int length)
{
int[] indexes = new int[length];
char[] current = new char[length];
for (int i=0; i < length; i++)
{
current[i] = chars[0];
}
do
{
yield return new string(current);
}
while (Increment(indexes, current, chars));
}
private static bool Increment(int[] indexes, char[] current, char[] chars)
{
int position = indexes.Length-1;
while (position >= 0)
{
indexes[position]++;
if (indexes[position] < chars.Length)
{
current[position] = chars[indexes[position]];
return true;
}
indexes[position] = 0;
current[position] = chars[0];
position--;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8626 次 |
最近记录: |