Wednesday, November 27, 2013

Dot Net: Collections

Count the frequency of different words in a sentence.

Objective:
To choose appropriate collection class for storing key/value pair.

Problem Statement:
Write a program to create a list of words present in a sentence passed from command line. The list also contains count of the appearance of each word in that sentence. The program has to display the words in sorted order and its frequency.

If the input is: “DotNet is technology and DotNet is interoperable and DotNet is simple”.


Output should be:  [and = 2, DotNet =3, interoperable = 1, is = 3, simple =1, technology=1]

SOLUTION: 

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

namespace FrequencyCount
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the line of words:");
            string str = Console.ReadLine();
            //Console.WriteLine(str);

            SortedDictionary< string, int > sortedDictionary = new SortedDictionary< string, int >();

            string[] words = str.Split(' ');

            foreach (string item in words)
            {
                if (sortedDictionary.ContainsKey(item))
                {
                    int x = 0;
                    x = sortedDictionary[item];
                    sortedDictionary[item] = x + 1;
                    //sortedDictionary.Add(item,x+1);
                }
                else
                {
                    sortedDictionary.Add(item, 1);
                }
            }

            char[] tr = str.ToCharArray();

            //Printing
            foreach (var item in sortedDictionary)
            {
                Console.WriteLine(item.Key + " " + item.Value);
            }
        }
    }

}

No comments:

Post a Comment