Anagrams method in C#

Given a string array called words, group all the words those are generated by same characters. For example,

input : {“bat”, “tar”, “xyz”, “tab”, “rat” }

output: an ArrayList [{“bat”,”tab”}, {“tar”,”rat”}, {“xyz”}]

 

class AnagramsMethod
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
string[] words = { “bat”, “tar”, “xyz”, “tab”, “rat” };
for (int i = 0; i < words.Length; ++i)
{
string temp1 = sortString(words[i]), temp2 = words[i];
if (ItemContains(al, words[i]))
{
for (int j = i + 1; j < words.Length; ++j)
{
string str1 = sortString(words[j]);
if (temp1.Equals(str1))
{
temp2 += “,” + words[j];
}
}
al.Add(temp2);
}
}

print(al);
}

private static void print(ArrayList al)
{
foreach (var item in al)
{
Console.WriteLine(Convert.ToString(item));
}
Console.ReadKey();
}

private static bool ItemContains(ArrayList p, string str)
{
foreach (string item in p)
{
if (item.Contains(str))
{
return false;
}
}
return true;
}

private static string sortString(string p)
{
char[] ch = p.ToCharArray();
Array.Sort(ch);
return new string(ch);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s