Print the most repeated word in a book using hash table

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string book = "one two two three three three four four four four";

            Regex reg = new Regex(" ");

            string[] wordArray = reg.Split(book);

            Hashtable myHashTable = new Hashtable();

            for (int i = 0; i < wordArray.Length; i++)

            {

                wordArray[i] = wordArray[i].Trim();

                if (wordArray[i] != "")

                {

                    if (myHashTable.ContainsKey(wordArray[i]))

                        myHashTable[wordArray[i]] = int.Parse(myHashTable[wordArray[i]].ToString()) + 1;

                    else

                        myHashTable.Add(wordArray[i], int.Parse("1"));

                }

            }

            Console.WriteLine("==========");

            Console.WriteLine("Hashtable:");

            Console.WriteLine("==========");

            foreach (DictionaryEntry entry in myHashTable)

                Console.WriteLine("{0} –> {1}", entry.Key, entry.Value);

            Array keys = Array.CreateInstance(typeof(string), myHashTable.Count);

            myHashTable.Keys.CopyTo(keys, 0);

            Array values = Array.CreateInstance(typeof(int), myHashTable.Count);

            myHashTable.Values.CopyTo(values, 0);

            Array.Sort(values, keys);

            Console.WriteLine("=====================");

            Console.WriteLine("Max repeated word(s):");

            Console.WriteLine("=====================");

            for (int i = values.Length – 1; i >= 0; i–)

            {

                if (i > 0)

                {

                    Console.WriteLine("{0} –> {1}", keys.GetValue(i), values.GetValue(i));

                    if ((int)values.GetValue(i) != (int)values.GetValue(i – 1))

                        break;

                }

                else

                    Console.WriteLine("{0} –> {1}", keys.GetValue(i), values.GetValue(i));

            }

        }

    }

}

 

==========
Hashtable:
==========
one –> 1
three –> 3
four –> 4
two –> 2
=====================
Max repeated word(s):
=====================
four –> 4
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