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.
Example:
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;
                }
                else
                {
                    ht.Add(GetSortedCharString(strArray[i]), strArray[i]);
                }
            }
            foreach (DictionaryEntry entry in ht)
            {
                Console.Write("{" + entry.Value + "}" + " ");
            }
            Console.WriteLine();
        }

        public static string GetSortedCharString(string str)
        {
            char[] chArray = str.ToCharArray();
            Array.Sort<char>(chArray);
            return (new string(chArray));
        }
    }
}

Output
=======
{rat, tar} {xyz} {bat, tab}
Press any key to continue . . .
Advertisements
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:

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