【问题标题】:Find All Possible Permutations In Certain Range C#查找特定范围内所有可能的排列 C#
【发布时间】:2015-09-30 21:58:43
【问题描述】:
【问题讨论】:
标签:
c#
permutation
stocks
【解决方案1】:
使用 Eric Lippert 的Cartesian Product,
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int maxlen = 3;
var query = Enumerable.Range(1, maxlen)
.SelectMany(i => Enumerable.Repeat(chars, i)
.CartesianProduct()
.Select(x => String.Concat(x)));
foreach(var str in query)
{
Console.WriteLine(str);
}
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;
}
【解决方案2】:
不确定它有多快,但当我需要做类似的事情时,我做了以下事情:
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 个字符输入作为前面的字符串的第三个函数将为您提供三个字符集。
26*26*26 是很多输出,但上面的模式应该会为您提供。