2016-04-27 32 views
1

根據輸入的牌照(例如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,但我不能......

+5

發佈你已經嘗試過的,如果它工作或沒有關係,無所謂噸。 – Xiaoy312

回答

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); 
+0

偉大的答案@ArturoMenchaca - 我使用這個,但如果我想所有組合爲「1」調整爲「我」和「L」,這是如何最好地實現?我曾嘗試將代碼調整爲的字典,但後來我開始懷疑它是否可行,然後我複製並粘貼了兩個變體的代碼,然後將結果合併爲一個不同的集合。只是想知道它應該如何完成。 –

+0

@DevologyLtd:你可以像你說的那樣使用一個char [],然後在遞歸調用之前在'if(replacements.ContainsKey ...'statement add'foreach(var replace in replacements [original [index]])''並用'current + replace'替換調用'current + replacements [original [index]]'。 –

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);