ptrelford

Permutations

Jul 13th, 2013
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using System.Collections.Generic;
  2.  
  3. class Program
  4. {
  5.     static Dictionary<int, string> digitToChars =
  6.         new Dictionary<int, string>
  7.             { { 0, "0"},
  8.                 { 1, "1"},
  9.                 { 2, "ABC"},
  10.                 { 3, "DEF"},
  11.                 { 4, "GHI"},
  12.                 { 5, "JKL"},
  13.                 { 6, "MNO"},
  14.                 { 7, "PQRS"},
  15.                 { 8, "TUV"},
  16.                 { 9, "WXYZ"}
  17.             };
  18.  
  19.     static IEnumerable<string> PermuteDigitsRec(string digits)
  20.     {
  21.         if (digits.Length == 0)
  22.         {
  23.             yield return "";
  24.             yield break;
  25.         }
  26.         var n = digits[0] - '0';
  27.         var tail = digits.Substring(1);
  28.         var chars = digitToChars[n];
  29.         foreach (var s in PermuteDigitsRec(tail))
  30.         {
  31.             foreach (var c in chars)
  32.             {
  33.                 yield return c + s;
  34.             }
  35.         }
  36.     }
  37.  
  38.     static string[] PermuteDigits(string digits)
  39.     {
  40.         var words = new List<string>();
  41.         words.Add("");
  42.         foreach (var digit in digits)
  43.         {
  44.             List<string> previous = words;
  45.             words = new List<string>();
  46.             int n = digit - '0';
  47.             foreach (var c in digitToChars[n])
  48.             {
  49.                 foreach(var word in previous)
  50.                 {
  51.                     words.Add(word+c);
  52.                 }
  53.             }
  54.         }
  55.         return words.ToArray();
  56.     }
  57.  
  58.     static void Main(string[] args)
  59.     {
  60.         var words = PermuteDigits("3663");
  61.         foreach(var x in words) System.Diagnostics.Debug.WriteLine(x);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment