Find all symmetric pairs from a given array in C#

Input: arr[,] = {{11, 20}, {30, 40}, {5, 10}, {40, 30}, {10, 5}}
Output: (30, 40) , (5, 10)
Explanation: (a,b),(c,d) this will be symmetric is a=d and b=c.
Logic: Think of one pair as key-value pair and add them in a dictionary. 
Now loop over the array and first check whether current pair's second 
element exists in dictionary or not if not then insert this current 
pair as key-value pair. If it exists then check whether first
element of this pair equals to dictionary value. 

static void Main(string[] args)
        {
            int[,] arrInput = new int[,] { { 11, 20 }, { 30, 40 }, { 5, 10 }, { 40, 30 }, { 10, 5 } };
            Dictionary<int, int> dict = new Dictionary<int, int>();
            int key = 0, value = 0, temp = 0;
            for (int i = 0; i < arrInput.GetLength(0); ++i)
            {
                key = arrInput[i, 0];
                value = arrInput[i, 1];

                if (dict.Keys.Any(x => x == value))
                {
                    temp = dict.Keys.Where(x => x == value).Single();
                    if (key == dict[temp])
                    {
                        Console.WriteLine(string.Format("key: {0}, Value: {1}", value, key));
                    }
                    else
                    {
                        dict.Add(key, value);
                    }
                }
                else
                {
                    dict.Add(key, value);
                }
            }
            Console.ReadKey();
        }
Advertisements

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