利用我对Looking at each combination in jagged array的回答中的算法可以轻松完成:
public static class Algorithms
{
public static IEnumerable<string> GetCombinations(this char[][] input)
{
var result = new char[input.Length];
var indices = new int[input.Length];
for (int pos = 0, index = 0; ;)
{
for (; pos < input.Length; pos++, index = 0)
{
indices[pos] = index;
result[pos] = input[pos][index];
}
yield return new string(result);
do
{
if (pos == 0) yield break;
index = indices[--pos] + 1;
}
while (index >= input[pos].Length);
}
}
}
通过添加以下方法:
public static IEnumerable<string> GetCombinations(this string input, Dictionary<char, char> replacements)
{
return input.Select(c =>
{
char r;
return replacements.TryGetValue(c, out r) && c != r ? new[] { c, r } : new[] { c };
}).ToArray().GetCombinations();
}
示例用法:
var replacements = new Dictionary<char, char> { { '1', 'I' }, { '3', '8' }, { 'A', 'H' }, { '0', 'O' }, { 'O', '0' } };
var test = "ABC123".GetCombinations(replacements);
foreach (var comb in test) Console.WriteLine(comb);