Grouping Anagram Sets

Given a set of words in a dictionary, write a program to group all words which are anagrams of each other in to sets.
Input: "bat", "rat", "xyz", "tab", "tar"
Output: {rat, tar} {xyz} {bat, tab}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            string[] strArray = { "bat", "rat", "xyz", "tab", "tar" };
            Hashtable ht = new Hashtable();
            for (int i = 0; i < strArray.Length; i++)
                if (ht.Contains(GetSortedCharString(strArray[i])))
                    string tempStr = (string) ht[GetSortedCharString(strArray[i])];
                    tempStr = tempStr + ", " + strArray[i];
                    ht[GetSortedCharString(strArray[i])] = tempStr;
                    ht.Add(GetSortedCharString(strArray[i]), strArray[i]);
            foreach (DictionaryEntry entry in ht)
                Console.Write("{" + entry.Value + "}" + " ");

        public static string GetSortedCharString(string str)
            char[] chArray = str.ToCharArray();
            return (new string(chArray));

{rat, tar} {xyz} {bat, tab}
Press any key to continue . . .
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s