Finding a List of Anagrams in C#

10/20/2009

This is a very simple algorithm that I created for a game that I'm working on. The game is a word game for smaller children and one of the things that it needs to do is anagrams. So I had to come up with a function to help me find them:

   1: public static Dictionary<string, System.Collections.Generic.List<string>> GetAnagramEquivalents(System.Collections.Generic.List<string> InputArray)
   2: {
   3:     Dictionary<string, System.Collections.Generic.List<string>> ReturnList = new Dictionary<string, System.Collections.Generic.List<string>>();
   4:     for (int x = 0; x < InputArray.Count; ++x)
   5:     {
   6:         char[] InputCharArray=InputArray[x].ToCharArray();
   7:         Array.Sort(InputCharArray);
   8:         string InputString = new string(InputCharArray);
   9:         if (ReturnList.ContainsKey(InputString))
  10:         {
  11:             ReturnList[InputString].Add(InputArray[x]);
  12:         }
  13:         else
  14:         {
  15:             ReturnList.Add(InputString, new System.Collections.Generic.List<string>());
  16:             ReturnList[InputString].Add(InputArray[x]);
  17:         }
  18:     }
  19:     return ReturnList;
  20: }

The code above is very basic.  But the general idea is that with a set of words, if you sort the letters in alphabetical order you end up with an equivalent string. For instance both car and arc would be acr when sorted. Thus they are equivalent and anagrams of one another. So all you need to do is pass in a list of words and it passes back a dictionary of anagrams. That's all there is to it. So try it out, leave feedback, and happy coding.



Comments