Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void printAnagramList(String[] words)
- {
- // Store anagram groups
- var groupings = new Dictionary<string, string>();
- for (int i = 1; i < words.Length; i++)
- {
- var ws = GetSortedWord(words[i]);
- for (int j = (i + 1); j < words.Length; j++)
- {
- char[] word2 = words[j].ToCharArray();
- Array.Sort(word2);
- // Helpful to compare things later
- var wsss = (new string(word2));
- // If the sorted string are equal, they have the same length and letter
- // occurrences. However, we don't want to deal with them if they are the
- // exact same word, which can happen in subsequent loops
- if (ws.Equals(wss) && !words[i].Equals(words[j]))
- {
- // if our groupings already contain the key, append our current word
- if (groupings.ContainsKey(ws))
- {
- // if the word is already in the group, don't add it again
- if (!groupings[ws].Split(',').Contains(words[j]))
- {
- groupings[ws] += "," + words[j];
- }
- else
- {
- // we don't have a new key/group started yet, let's create one
- groupings.Add(ws, words[i] + "," + words[j]);
- }
- }
- }
- }
- // output all groupings on their own line
- foreach (var key in groupings.Keys)
- {
- Console.WriteLine(groupings[key]);
- }}
- }
- public static string GetSortedWord(string word)
- {
- char[] word_char = word.ToCharArray();
- Array.Sort(word_char);
- return (new string(word_char));
- }
Add Comment
Please, Sign In to add comment