Intersection of two integer arrays

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Intersection of two integer arrays
            int[] A = { 1, 2, 3, 4, 5, 6, 6, 7, 9, 4 };
            int[] B = { 0, 3, 4, 4, 4, 5, 5, 6 };
            Hashtable ht = new Hashtable();
            for (int i = 0; i < A.Length; i++)
            {
                if (ht.Contains(A[i]))
                {
                    ht[A[i]] = int.Parse(ht[A[i]].ToString()) + 1;
                }
                else
                {
                    ht.Add(A[i], 1);
                }
            }
            Console.Write("Common elements = ");
            for (int i = 0; i < B.Length; i++)
            {
                if (ht.Contains(B[i]) && int.Parse(ht[B[i]].ToString()) != 0)
                {
                    ht[B[i]] = int.Parse(ht[B[i]].ToString()) - 1;
                    Console.Write(B[i].ToString() + " ");
                }
            }
            Console.WriteLine();
        }
    }
}

Output
=======
Common elements = 3 4 4 5 6
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