我找到的最接近的SO主题是:Listing all permutations of a string/integer
但是,我如何将这个用于字符串中每个位置的不同字符集?
示例:我指定字符串长度为“3”。前两个位置应为“a”或“b”,但最后一个位置应为“1”或“2”,例如:
aa1
ba1
ab1
bb1
aa2
ab2
ba2
bb2
答案 0 :(得分:2)
如果长度已修复,您可以使用此简单查询创建cartesian product:
string chars = "ab";
int[] digits = { 1, 2 };
var query = from c1 in chars
from c2 in chars
from d1 in digits
select string.Format("{0}{1}{2}", c1, c2, d1);
string[] possibleCombinations = query.ToArray();
结果:
aa1
aa2
ab1
ab2
ba1
ba2
bb1
bb2
修改:对于它的价值,lambda按要求提供(查询语法更具可读性):
possibleCombinations = chars
.SelectMany(c1 => chars
.SelectMany(c2 => digits
.Select(d1 => string.Format("{0}{1}{2}", c1, c2, d1))))
.ToArray();
如果你需要一种处理动态长度的方法,你可以看一下:
Dynamic Generation of All Possible Combinations of Index of an Array
答案 1 :(得分:2)
使用此代码:
public static List<string> GenerateCombinations(char[][] characters)
{
var combinations = new List<string>();
GenerateCombinations(0, characters, new char[characters.GetLength(0)], combinations);
return combinations;
}
private static void GenerateCombinations(int level, char[][] characters, char[] current, List<string> combinations)
{
if (level == characters.GetLength(0))
{
combinations.Add(new string(current));
return;
}
foreach (var character in characters[level])
{
current[level] = character;
GenerateCombinations(level + 1, characters, current, combinations);
}
}
使用它的例子:
public static void Main()
{
var characters = new[]
{
new[] { 'a', 'b' },
new[] { 'a', 'b' },
new[] { '1', '2' }
};
var combinations = GenerateCombinations(characters);
foreach (var combination in combinations)
{
Console.WriteLine(combination);
}
}
输出:
aa1
aa2
ab1
ab2
ba1
ba2
bb1
bb2