C# 在一定范围内找出所有可能的排列
我想制作一个程序,从Yahoo Finance中查找所有有效的股票符号,我已经找到了: 然而,我不想从A-Z再到AA-AZ再到ABA-ABZ等等。最好的方法是什么?更清楚的例子:一个B C D ect。C# 在一定范围内找出所有可能的排列,c#,permutation,stocks,C#,Permutation,Stocks,我想制作一个程序,从Yahoo Finance中查找所有有效的股票符号,我已经找到了: 然而,我不想从A-Z再到AA-AZ再到ABA-ABZ等等。最好的方法是什么?更清楚的例子:一个B C D ect。 AA AB AC AD等。ABA ABB ABC ABD等。不确定它有多快,但当我需要做类似的事情时,我做了以下几点: for (int i = 0; i < numCols && i < 26; i++) {
AA AB AC AD等。ABA ABB ABC ABD等。不确定它有多快,但当我需要做类似的事情时,我做了以下几点:
for (int i = 0; i < numCols && i < 26; i++)
{
char start = 'A';
char colChar = (char)(start + (char)(i));
Console.WriteLine(string.Format("{0}", colChar), typeof(string));
}
for (int i = 26; i < 52 && i < numCols; i++)
{
char start = 'A';
char colChar = (char)(start + (char)(i-26));
Console.WriteLine(string.Format("A{0}", colChar), typeof(string));
}
第二个for循环显然只返回AA到AZ,但是如果你把它放在一个函数中,把第一个a作为输入,那么你可以通过a-Z循环第一个字符,你就得到了所有两个字符的结果。创建第三个函数,输入2个字符作为前面的字符串,将得到3个字符集
26*26*26是一个很大的输出,但是上面的模式应该可以满足您的需要。使用Eric Lippert的
PS:为了完整性:
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var sequence in sequences)
{
var s = sequence; // don't close over the loop variable
// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] { item });
}
return result;
}
看看
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
// base case:
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var sequence in sequences)
{
var s = sequence; // don't close over the loop variable
// recursive case: use SelectMany to build the new product out of the old one
result =
from seq in result
from item in s
select seq.Concat(new[] { item });
}
return result;
}