具有多字符替换的字符串组合

时间:2016-04-27 21:48:28

标签: c# algorithm combinations

根据输入的牌照(例如ABC123)和替换值列表(例如1替换为I)。我需要得到所有可能的组合。

例如:

1 => I
3 => B
A => H
0 (zero) => O
O => 0 (zero)

输入:

  

ABC123

预期产出:

  

ABC123,       ABCI23,       ABCI28,       ABC128,       HBC123,       HBCI23,       HBCI28,       HBC128

我尝试了String Combinations With Character Replacement,但我无法......

2 个答案:

答案 0 :(得分:2)

你可以使用递归,迭代每个字符并使用原始字符和替换来递归调用,如下所示:

public static IEnumerable<string> Combinations(string s, Dictionary<char, char> replacements)
{
    return Combinations(s, replacements, 0, string.Empty);
}

private static IEnumerable<string> Combinations(string original, Dictionary<char, char> replacements, int index, string current)
{
    if (index == original.Length) yield return current;
    else
    {
        foreach (var item in Combinations(original, replacements, index + 1, current + original[index]))
            yield return item;

        if (replacements.ContainsKey(original[index]))
            foreach (var item in Combinations(original, replacements, index + 1, current + replacements[original[index]]))
                yield return item;
    }
}

并像这样调用这些方法:

Dictionary<char, char> dict = new Dictionary<char,char>();
dict['1'] = 'I';
dict['3'] = 'B';
dict['A'] = 'H';
dict['O'] = '0';
dict['0'] = 'O';

var combs = Combinations("ABC123", dict);

答案 1 :(得分:0)

可以通过我对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);