Guest User

Untitled

a guest
Dec 15th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public static void printAnagramList(String[] words)
  2. {
  3. // Store anagram groups
  4. var groupings = new Dictionary<string, string>();
  5. for (int i = 1; i < words.Length; i++)
  6. {
  7. var ws = GetSortedWord(words[i]);
  8. for (int j = (i + 1); j < words.Length; j++)
  9. {
  10. char[] word2 = words[j].ToCharArray();
  11. Array.Sort(word2);
  12. // Helpful to compare things later
  13. var wsss = (new string(word2));
  14. // If the sorted string are equal, they have the same length and letter
  15. // occurrences. However, we don't want to deal with them if they are the
  16. // exact same word, which can happen in subsequent loops
  17. if (ws.Equals(wss) && !words[i].Equals(words[j]))
  18. {
  19. // if our groupings already contain the key, append our current word
  20. if (groupings.ContainsKey(ws))
  21. {
  22. // if the word is already in the group, don't add it again
  23. if (!groupings[ws].Split(',').Contains(words[j]))
  24. {
  25. groupings[ws] += "," + words[j];
  26. }
  27. else
  28. {
  29. // we don't have a new key/group started yet, let's create one
  30. groupings.Add(ws, words[i] + "," + words[j]);
  31. }
  32. }
  33. }
  34. }
  35. // output all groupings on their own line
  36. foreach (var key in groupings.Keys)
  37. {
  38. Console.WriteLine(groupings[key]);
  39. }}
  40. }
  41.  
  42. public static string GetSortedWord(string word)
  43. {
  44. char[] word_char = word.ToCharArray();
  45. Array.Sort(word_char);
  46. return (new string(word_char));
  47. }
Add Comment
Please, Sign In to add comment