[ Algrorithm ] Complement of set : Symmetric difference C# code

Problem: Given two array are:
a={2, 4, 5, 9, 0};
b={ 4, 1, 8, 7, 9, 0 }

The result set: c={2,5,4,1,8,7,9,0}

This is the symmetric difference of sets a and b is variously written as A circleminus B, Adel B, A+B (Borowski and Borwein 1991) .

My solution:
- Loop through a then b;
- if one a's element is equal to b's one then break
- if no b's element is equal to a's one then copy it to the declared array result;
- then append all of b to result.



C# code  Symmetric difference

    static void Main(string[] args)
        {           
            //given array
            int[] a = new int[5]{2, 4, 5, 9, 0};
            int[] b = new int[6] { 4, 1, 8, 7, 9, 0 };

// this dictionary entry is going to contain pair length and array which are returned from the function union
            Dictionary<int,int[]> c= symdif(a,b,5,6);

            // len and r are variables which are used for receiving from the dictionary entry c


            int len = c.Keys.First();
            int[] r = c.Values.First();

// display elements in the array r


            for (int x = 0; x < len; x++ )
                Console.WriteLine(r[x]);


            Console.ReadKey();

        }
        //Symmetric difference operation
        static Dictionary<int,int[]> symdif(int[] inarray1, int[] inarray2, int alength1, int alength2)
        {
            int[] result = new int[alength1 + alength2];
            int resultlength=0;

            for(int i=0; i<alength1;i++)
            {
                bool insided = false;

                for(int j=0; j<alength2; j++)
                {
                    if (inarray1[i] == inarray2[j])
                    { insided = true;
                        break; }
                }

                if(insided==false)
                {
                    result[resultlength] = inarray1[i];
                    resultlength = resultlength + 1;
                }

            }
            for (int k = 0; k < alength2; k++)
            {

                result[resultlength+k] = inarray2[k];
            }

            resultlength = resultlength + alength2;
            Dictionary<int, int[]> r = new Dictionary<int, int[]>();
            r.Add(resultlength, result);

            return r;
        }
Share on Google Plus

About Chien

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment