Advertisement
sylviapsh

Messages In A Bottle

Feb 4th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class MessagesInABottle
  5. {
  6.   static void Main()
  7.   {
  8.     string message = Console.ReadLine(),
  9.            cipher = Console.ReadLine();
  10.     Dictionary<string, char> cipherParts = new Dictionary<string, char>();
  11.  
  12.     char currentLetter = '.';
  13.     string currentDigit = "";
  14.     foreach (char symbol in cipher)
  15.     {
  16.       if (char.IsLetter(symbol))
  17.       {  
  18.         if (currentDigit != "")
  19.         {
  20.           cipherParts.Add(currentDigit, currentLetter);
  21.           currentDigit = "";
  22.         }
  23.         currentLetter = symbol;
  24.       }
  25.       if (char.IsDigit(symbol))
  26.       {
  27.         currentDigit += symbol;
  28.       }
  29.     }
  30.     if (currentDigit != "")
  31.     {
  32.       cipherParts.Add(currentDigit, currentLetter);
  33.     }
  34.  
  35.     List<string[,]> decodedRemaining= new List<string[,]>(); // 0 for decoded, 1 for remaining
  36.     string[,] initialState = new string [1,2];
  37.     initialState[0, 0] = "";
  38.     initialState[0, 1] = message;
  39.     decodedRemaining.Add(initialState);
  40.     List<string> results = new List<string>();
  41.     int index=0;
  42.     while (index < decodedRemaining.Count)
  43.     {
  44.  
  45.       string[,] currentState = decodedRemaining[index];
  46.  
  47.       foreach (var element in cipherParts.Keys)
  48.       {
  49.  
  50.         if (currentState[0, 1].StartsWith(element))
  51.         {
  52.           char letterToAdd;
  53.           cipherParts.TryGetValue(element, out letterToAdd);
  54.  
  55.           string[,] decodingInProgress = new string[1, 2];
  56.           decodingInProgress[0, 0] = currentState[0, 0] + letterToAdd.ToString();
  57.  
  58.           decodingInProgress[0, 1] = currentState.GetValue(0, 1).ToString().Substring(element.Length);
  59.           if (decodingInProgress[0, 1] == "")
  60.           {
  61.             results.Add(decodingInProgress[0,0]);
  62.           }
  63.           else
  64.           {
  65.             decodedRemaining.Add(decodingInProgress);
  66.           }
  67.         }
  68.       }
  69.    
  70.       index++;
  71.       //decodedRemaining.RemoveAt(index-1);
  72.     }
  73.  
  74.     results.Sort();
  75.     //Print result
  76.     Console.WriteLine(results.Count);
  77.     for (int i = 0; i < results.Count; i++)
  78.     {
  79.       Console.WriteLine(results[i]);
  80.     }
  81.   }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement