Skip to content

Instantly share code, notes, and snippets.

@teeheehee
Created December 12, 2017 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teeheehee/03f293c7c87580b0e934e72d6665a0d6 to your computer and use it in GitHub Desktop.
Save teeheehee/03f293c7c87580b0e934e72d6665a0d6 to your computer and use it in GitHub Desktop.
Anagrams interview test with some broken 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment